Thursday, December 14, 2006

* Dynamic Binding : Performance

All of us know the power of late binding or dynamic binding.

Using this feature of .NET we can load any assembly at runtime and create an instance of a type in that assembly at runtime.

Some of the commonly used APIs used for this task are :



Today i decided to see the performance impact of dynamic binding and the results which i got are really scary.

Here are the test details :

Created an class library with following code:

namespace VikasGoyal
public class MathLibrary
public double increment(double value)
return value + 1;

A simple class with a method which increments the input value by 1 and returns the incremented value.

Created a console application which creates instance of MathLibrary and calls increment method in a for loop. The loop count is 9,000,000.

The console application utilizes library in three different ways :

1. Static linking

MathLibrary was added as a reference, instance created and method called.

VikasGoyal.MathLibrary ml = new VikasGoyal.MathLibrary();
value = ml.increment(value);

2. Creating type dynamically

MathLibrary was added as a reference but type instance created dynamically.

className = typeof(VikasGoyal.MathLibrary);

System.Object target = Activator.CreateInstance(className);
value = (double)className.InvokeMember("increment", System.Reflection.BindingFlags.InvokeMethod, null, target, new object[] { value });

3. Assembly Loaded dynamically

No reference of MathLibrary was added at build time to Console application.

Library was loaded at runtime and instances created at runtime

Assembly asm = Assembly.Load("MathLibrary");
className = asm.GetType("VikasGoyal.MathLibrary");

Following is time taken to complete the above mentioned loops by various methods:

1. Static Linking : 0.38 secs

2. Creating type dynamically : 47.7 secs

3. Assembly Loaded dynamically : 6 min 10 sec.

The performance difference seems to be huge. Multiple tests were done to ensure consistency of results.

Soon i will publish the results with as calling application to verify if does some optimizations for assembly loading.

Other Posts

No comments:

Post a Comment