.NET 2.0 Performance Guidelines - Reflection and Late Binding

From Guidance Share

Revision as of 00:50, 13 December 2007; JD (Talk | contribs)
(diff) ←Older revision | Current revision | Newer revision→ (diff)
Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, Rico Mariani, and Alex Mackman


Prefer Early Binding and Explicit Types Rather Than Reflection

Visual Basic .NET uses reflection implicitly when you declare the type as object. In C#, you use reflection explicitly. You should avoid reflection wherever possible by using early binding and declaring types explicitly.

Some examples where you use reflection explicitly in C# are when you perform any of the following operations:

  • Type comparisons using TypeOf, GetType, and IsInstanceOfType.
  • Late bound enumeration using Type.GetFields.
  • Late bound execution using Type.InvokeMember.

Avoid Late Binding

Early binding allows the compiler to identify the specific type required and perform optimizations that are used at run time. Late binding defers the type identification process until run time and requires extra processing instructions to allow type identification and initialization. The following code loads a type at run time.

Assembly asm = System.Reflection.Assembly.LoadFrom("C:\\myAssembly.dll");
Type myType = asm.GetType("myAssembly.MyTypeName");
Object myinstance = Activator.CreateInstance(myType);

This is the equivalent of the following.

MyTypeName myinstance = new MyTypeName();

In some cases, you need dynamic execution of types but when performance is critical, avoid late binding.

Avoid Using System.Object in Performance-Critical Code Paths

The System.Object data type can represent any value or reference type but requires late bound calls to execute methods and access properties. Avoid using the Object type when performance of your code is critical.

The Visual Basic .NET compiler implicitly uses reflection if you declare the type as Object.

Dim obj As Object
Set Obj = new CustomType()

Note This is a Visual Basic .NET specific issue. C# has no such problem.

Enable Option Explicit and Option Strict in Visual Basic.NET

By default, Visual Basic .NET allows late bound code. Set the Strict and Explicit properties to true to force Visual Basic .NET to not allow late bound code. In Visual Studio .NET, you can access these properties through the Project Properties dialog box. If you use the command line compiler Vbc.exe to compile your code, use the /optionexplicit and /optionstrict flags.

Personal tools