Click here to Skip to main content
Licence CPOL
First Posted 25 Jan 2012
Views 513
Bookmarked 2 times

Alternative to Activator.CreateInstance

Using expressions, you can achieve a faster result with less code.public static T New(){ Type t = typeof(T); Func method = Expression.Lambda>(Expression.Block(t, new Expression[] { Expression.New(t) })).Compile(); return method();}Furthermore, this can...
Using expressions, you can achieve a faster result with less code.
 
public static T New<T>()
{
    Type t = typeof(T);
    Func<T> method = Expression.Lambda<Func<T>>(Expression.Block(t, new Expression[] { Expression.New(t) })).Compile();
 
    return method();
}
 
Furthermore, this can be refined further by capturing the method into a dictionary and saving it off for future use. As an example, you can see this tip[^], which does something like this.
 
From my own testing of 1000 iterations of both, mine (without caching) was 148 milliseconds, while your original was 220 milliseconds.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Andrew Rissing

Software Developer (Senior)

United States United States

Member

Since I've begun my profession as a software developer, I've learned one important fact - change is inevitable. Requirements change, code changes, and life changes.
 
So..If you're not moving forward, you're moving backwards.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralReason for my vote of 1 No DM or Expressions are needed for ... Pinmembernonexisto2:15 26 Jan '12  
GeneralRe: Corrected. I removed the type constraint. I didn't realize... PinmemberAndrew Rissing3:39 26 Jan '12  
GeneralI'd have to agree with your comment. The big bottleneck slow... PinmemberDean Oliver18:40 25 Jan '12  
GeneralI am aware of this alternative. However my results where wel... PinmemberDean Oliver8:44 25 Jan '12  
GeneralRe: The overhead in your method may likely be due to the dynamic... PinmemberAndrew Rissing9:36 25 Jan '12  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 26 Jan 2012
Article Copyright 2012 by Andrew Rissing
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid