Click here to Skip to main content
15,114,611 members
Articles / Programming Languages / C#
Alternative
Tip/Trick
Posted 25 Jan 2012

Tagged as

Stats

16.6K views
3 bookmarked

Alternative to Activator.CreateInstance

Rate me:
Please Sign up or sign in to vote.
4.67/5 (4 votes)
26 Jan 2012CPOL
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.

C#
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)

Share

About the Author

Andrew Rissing
Architect
United States United States
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.

Comments and Discussions

 
GeneralReason for my vote of 1 No DM or Expressions are needed for ... Pin
nonexisto26-Jan-12 3:15
Membernonexisto26-Jan-12 3:15 
GeneralRe: Corrected. I removed the type constraint. I didn't realize... Pin
Andrew Rissing26-Jan-12 4:39
MemberAndrew Rissing26-Jan-12 4:39 
GeneralI'd have to agree with your comment. The big bottleneck slow... Pin
Dean Oliver25-Jan-12 19:40
MemberDean Oliver25-Jan-12 19:40 
GeneralI am aware of this alternative. However my results where wel... Pin
Dean Oliver25-Jan-12 9:44
MemberDean Oliver25-Jan-12 9:44 
I am aware of this alternative. However my results where well in favour of the DynamicMethod implementation over the ExpressionTree. Expression lambda was 4x slower than the DynamicMethod. Maybe you can share your code so I can compare. But from my own tests Expressions are far slower. DynamicMethod will in most cases always be faster because it's directly generated to IL.
GeneralRe: The overhead in your method may likely be due to the dynamic... Pin
Andrew Rissing25-Jan-12 10:36
MemberAndrew Rissing25-Jan-12 10:36 

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

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