Object Creation using Lambda Expressions Part 1

Object creation using Lambda Expressions, a fast alternative to Activator.CreateInstance.

When it comes to creating objects of a generic type the typical solution is to use Activator.CreateInstance.

The solution does provide a simple way of creating generic objects, but it comes at a performance cost.  It is relatively slow to create an object this way and in performance critical areas of code the impact may well be significant.

I’m working on something at the moment that needs to create generic objects and quite possibly a lot of generic objects so I went hunting for a solution that was quicker.

A search led me to this article by Roger Johansson which describes a solution that uses Linq Expressions to build a Lambda Expression that is much faster that the Activator solution:

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

Here is a version of that solution that creates an object creator (activator) for the first constructor found on the generic type passed in:

The object creator can be used as follows:

So how does this solution compare to Activator.CreateInstance?  The following graph shows the average time in microseconds (µs) per call.  This test was done on a Windows 10 PC with a relatively old Intel i7 CPU.  The time to create the same object where the type is known using the normal new() method is included for reference.


Graph1

So it’s slow, very slow to create an object using this method once.  But once the expression has been created and compiled, it can then be cached and re-used repeatedly to create instances of the same type using the same constructor.  The code to use the creator and cache the result is simply:

This is where it gets fast.  The next graph shows what happens when we cache the object creator and re-use it.

 

Graph2

 

Now the Lambda Expression is 7x faster than Activator.CreateInstance and only 4x slower than creating an object of known type using new().

So when you need to create generic objects and performance really matters try this solution.  In my next post I’ll refactor this into a static class with helper methods to facilitate ease of use.

Thanks to Roger for his post.

Please follow the link for Part 2:

Object Creation using Lambda Expressions Part 2

One thought on “Object Creation using Lambda Expressions Part 1

  1. Pingback: Object Creation using Lambda Expressions Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *