Let me open this post with this beautiful quote:
“Time felt slower when we do nothing but wait.”
– Toba Beta, My 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);
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!