Here's another quick tip; again... pun intended. If you are writing high performance dynamic code you have likely found yourself using the "Activator" to instantiate instances of objects. This is commonly the case when employing Inversion of Control (IoC) patterns, or using reflection to discover and create types at runtime. Here are a couple typical examples:
IFoo foo = (IFoo)Activator.CreateInstance(typeof(Foo));
IFoo foo = Activator.CreateInstance<Foo>();
These approaches can be perfectly reasonable until you are constructing the same types often (as with IoC) or you have more substantial performance requirements. So what's wrong with using the "Activator"? In a couple words... It's slow! Don't take my word for it. Build your own test rig and it should become obvious.

Still not sure? What you need is another point of reference, such as a more performant alternative. Here comes Lambda Expressions to the rescue. Lets see how we can leverage this capability to rival the Activator.
private static Func<T> GetConstructor<T>() where T : class, new()
{
ConstructorInfo constructorInfo = typeof(T).GetConstructor(new Type[0]);
return Expression.Lambda<Func<T>>(Expression.New(constructorInfo))
.Compile();
}
The above routine will create a compiled constructor for a given Type. Although you have to keep track of this state, it can easily be managed within a Type construction Factory such as those built into IoC Containers. With this method you can create as many instances as you need and then release the associated resources.
var constructor = GetConstructor<Foo>();
IFoo foo = constructor();
If we apply the same test rig used previously and retest with this approach, it is easy to see how things stack up.

Although not covered here, this sample can easily be extended to support parameterized constructors. Enjoy, and use in good health.
Tags: performance