Creating objects in .NET or any other language is an easy task, using it’s new() or equivalent keyword, but sometimes things are not that straightforward. There are many times when you don’t even know the type of object you will need to create.

Let’s take for example an entity mapper. It can need to map hundreds of thousands of records from a database, and normally you will use a “Generic Mapper” to create them.

Most people would use the .NET Activator class to do this:

public T Create<T>() {
    return Activator.CreateInstance(typeof(T)) as T;
}

While this is an easy and convenient approach, it’s painfully slow compared to a new() call.

Surfing the internet looking for some ideas, I found this article where you can see a pretty nifty idea to create zillions of objects much, much faster, using Linq expressions, rather than with Activator, that will allow you to do this:

ConstructorInfo ctor = typeof(Created).GetConstructors().First();
ObjectActivator<Created> createdActivator = GetActivator<Created>(ctor);
...
//create an instance:
Created instance = createdActivator (123, "Roger");

http://rogeralsing.com/2008/02/28/linq-expressions-creating-objects/

In this article they show you how to use Linq lambda expressions to create objects at a blazing fast speed, near the new() speed, giving you a good alternative for your mapper classes…

The results are really impressive, as the article shows, for a bulk of 1000000 (yeah, one million) objects:

Activator.CreateInstance: 8.74 sec
Linq Expressions: 0.104 sec

In some time, I’ll try to make a follow-up article for this one, showing you how to make your object factory using this method, but for the time being…

Enjoy it!

Follow me

Joan Vilariño

Senior .NET Developer at Ohpen
Developer for more than 25 years and IT, gadget, mobile and electronics enthusiast working and publishing from Barcelona.
Follow me