Mar 5 2010

When "Activator" is just to slow

Category: Tips and TricksJoeGeeky @ 05:00

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:

Comments

1.
pingback blog.cwa.me.uk says:

Pingback from blog.cwa.me.uk

The Morning Brew - Chris Alcock  » The Morning Brew #557

2.
Steve Steve Belgium says:

If you do have the where T : new() constraint you can just do

return new T();

Which will be the same as calling the ctor in normal code, if you don't have the constraint then the lambda is a really good way!

3.
Steve Steve Belgium says:

If you do have the where T : new() constraint you can just do

return new T();

Which will be the same as calling the ctor in normal code, if you don't have the constraint then the lambda is a really good way!

5.
Steve Steve Belgium says:

I really did not know that, Reflector even shows new T() in C# mode, but switching to IL reveals the actual code.

We learn something new everyday Smile

6.
Sohbet Sohbet Turkey says:

Hey Admin! Thanks, Forever web pages..

7.
trackback uberVU - social comments says:

Social comments and analytics for this post

This post was mentioned on Twitter by dotnetlinks: When "Activator" is just to slow by @JoeGeeky http://bit.ly/9yUSbp

8.
szybko schudnąć szybko schudnąć Poland says:

Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

9.
trackback DotNetKicks.com says:

When

You've been kicked (a good thing) - Trackback from DotNetKicks.com

10.
Don Don Germany says:

Do not limit yourself. Many writers restrict themselves to what they think they can do. Be sure you can gothat far as your mind will let you.

11.
Marlene Boham Marlene Boham United States says:

In That Respect there r surely a stack of points like that to take into consideration

12.
Tom Tom Germany says:

You mention an interesting point on that topic. For me you described it in a professional manner. I hope you will go further in this way, with your unique ability of posting

13.
Buddy Mathre Buddy Mathre United States says:

Definitely agree with what you stated. Your explanation was certainly the easiest to understand. I tell you, I usually get irked when folks discuss issues that they plainly do not know about. You managed to hit the nail right on the head and explained out everything without complication. Maybe, people can take a signal. Will likely be back to get more. Thanks

14.
John Kirk John Kirk United States says:

I like the blog, but could not find how to subscribe to receive the updates by email. Can you please let me know?

15.
Richard Dingwall Richard Dingwall United Kingdom says:

Neato. I love high performance CLR tips like this Smile

17.
Hatim Hatim Morocco says:

What did you use to compute the rates per seconds. just curious. Great Post though!

18.
Zins Tilgungsrechner Zins Tilgungsrechner Germany says:

Considerably, the post is actually the sweetest on this laudable topic. I harmonise with your conclusions and will thirstily look forward to your upcoming updates. Saying thanks will not just be enough, for the great lucidity in your writing style. I will instantly grab your rss feed to stay informed of any updates. Solid work and much success in your business dealings!

19.
Mayme Wiedmann Mayme Wiedmann says:

Heard about this site from my friend. He pointed me here and told me I’d find what I need. He was right! I got all the questions I had, answered. Didn’t even take long to find it. Love the fact that you made it so easy for people like me. More power

20.
prefabrykaty budowlane prefabrykaty budowlane Poland says:

That is nice to definitely find a site where the blogger knows what they are talking about.

21.
Ivory Stoffer Ivory Stoffer United Kingdom says:

Yet another nice post. There are very few sites that I’ve registered at in order to comment, but yours is one.  I love reading your articles and look forward to seeing new ones appear in my RSS reader.  Keep up the good work.

22.
Cruz Steinbacher Cruz Steinbacher United States says:

After reading a few of your posts, I really like what you have to say, how do I subscribe to your site?

23.
Herschel Fimbres Herschel Fimbres United States says:

I don't anyways agree with people, but I read a few posts here and like what you have to say, keep up the good work.

24.
China SEO China SEO United States says:

<P>I'm glad China is starting to loosen some of their restrictions on the internet.  Now more websites are accessible.</P>

25.
Tyson F. Gautreaux Tyson F. Gautreaux United States says:

I really enjoyed visitingyour blog. I will be back

26.
posadzki betonowe posadzki betonowe Poland says:

This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It?s the old what goes around comes around routine.

27.
dave dave United Kingdom says:

wow thanks for the tip - I'll try it in my code as we're tring to get the speed up a bit and activator is used fairly extensively.

28.
Talitha Ranke Talitha Ranke United States says:

Wonderful blog, some fascinating points. I remember 2 of days ago, I have visited a similar post.

29.
Ferdinand Reynolds Ferdinand Reynolds United States says:

The article is in reality the great on this worthy subject. I fit in with your conclusions and looking forward to your coming updates. Just saying thanks will not just be enough, for the fantastic clarity in your writing. I've grabbed your rss feed to stay informed of any updates. Gratifying work and much success in your business dealings! Sincerely, Kent

30.
Javier Lamarta Javier Lamarta United States says:

Interesting story, it reminds me of a post I saw submitted about a month ago. I dont remember the exact URL, but I believe it was by Gary Garret, are you familiar with them?

31.
Franklin Munoz Franklin Munoz United States says:

Hi just thought i would tell you something.. This is twice now i've landed on your blog in the last 3 days hunting for completely unrelated things. Spooky or what?

32.
Darcel Jarmon Darcel Jarmon United States says:

Wow, thank you for this post. It works like a charm. I'm sorry to say that I doubted this at first.

33.
Karine Stahlman Karine Stahlman United States says:

Heard about this site from my friend. He pointed me here and told me I’d find what I need. He was right! I got all the questions I had, answered. Didn’t even take long to find it. Love the fact that you made it so easy for people like me. More power

34.
Bennett Hicks Bennett Hicks United States says:

Thanks for taking the time to discuss this, I feel strongly about it and love understanding more on this subject. If feasible, as you obtain expertise, would you mind updating your weblog with more info? It's extremely useful for me.

35.
Morgan Zieler Morgan Zieler United States says:

It does seem that everybody is into this kind of stuff lately. Don’t really understand it though, but thanks for trying to explain it. Appreciate you shedding light into this matter. Keep it up

36.
Derrick Nieves Derrick Nieves United States says:

Well, this is my first visit for your weblog! We're a group of volunteers and starting a brand new initiative inside a community in the exact same specialized niche. Your weblog provided us useful info to operate on. You've carried out a marvellous work!

37.
Aisha Malone Aisha Malone United States says:

Great post and resource! Thanks for it, it was greatly admired.

38.
www.rss-link.de www.rss-link.de United States says:

Pretty impressive article. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your opinions. Any way I’ll be coming back and I hope you post again soon.

39.
Mathew day Mathew day United States says:

This post shows the information which is close to standard.
Hope next You will again post a nice Artical/Information.

Visit us:

Mathew Day:

www.mathewday.com

40.
pingback 13.myipgirl.com says:

Pingback from 13.myipgirl.com

Eldorado Fog Light Cadillac Seville, Cadillac Seville Aftermarket Performance Parts

41.
pingback softwaredeveloper.interactiveinfonet.info says:

Pingback from softwaredeveloper.interactiveinfonet.info

9000 developer iso software - Software developer - Software developer

42.
pingback softwareobjects.net says:

Pingback from softwareobjects.net

Best way to dynamically create classes instead of using a switch block » Technology Articles - Technology And Programming Articles

Comments are closed