Reflection provides the ability to examine and compare types, enumerate methods and fields, and dynamically create and execute types at runtime. Typically, all reflection costs are high, some reflection operations cost much more than others. Comparing types is the least expensive, while dynamically creating and executing is the most expensive. The late binding technique uses reflection internally and is an expensive operation that should be avoided in performance critical code.
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()
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.
In our next article we’ll discuss Code Acces Security guidelines.