Alternatives to Activator.CreateInstance – when milliseconds matter!

Hello World!

Let me open this post with this beautiful quote:

“Time felt slower when we do nothing but wait.” 

 Toba BetaMy Ancestor Was an Ancient Astronaut

On one such occasion, while waiting for a program to do what it should, I thought of analyzing the performance through Red Gate’s ANTS memory profiler and it showed that a significant bit of time was being spent in creating types in a reflective manner using Activator.CreateInstance. A quick Google for alternatives yielded some results that were nothing short of an eye opener for me! So this is sort of a “post-it” for myself and peers of various ways the community has come up with.

I. Roger Alsing’s LINQ way: as explained in his post here
This methodology makes use of an ObjectCreator delegate like so:

delegate T ObjectActivator<T>(params object[] args);

Once you implement the delegate as demonstrated by Roger, the invocation is pretty simple to read:

 ConstructorInfo ctor = typeof(Created).GetConstructors().First();
 ObjectActivator<Created> createdActivator = GetActivator<Created>(ctor);

 //create an instance:
 Created instance = createdActivator (123, "Roger");

II. Robert Jan Boeije’s extension method on System.Type as explained in his post here His way is using the power of compiled lambda expressions. (// TODO: something to learn) When you have this extension method in place, the call to create a new instance is as simple as this:

return typeof (T).New<T>(value);

That’s it!

III. Something similar by Steve Wilkes with performance statistics and insightful comments here

IV. Dean Oliver on CodeProject – Using the DynamicMethod class in the Reflection namespace Demonstrated here Here, Dean uses IL.Emit to optimize creation of instances. //TODO: read on how IL emit works!

V. Andrew Rissing on CodeProject: here Again, the magic is lambda expressions and the Func<> delegate Whoa! I guess that’s enough for now!

In summary, the lesson learnt for me is that no more Activator.CreateInstance in my code unless it is for a once per application lifecycle creation!

Happy Coding!

Advertisements
Tagged with:
Posted in .NET, C#, Lamda-Expression, Reflection

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

  • Comic for July 25, 2017
    Dilbert readers - Please visit Dilbert.com to read this feature. Due to changes with our feeds, we are now making this RSS feed a link to Dilbert.com.
%d bloggers like this: