Click here to Skip to main content
15,116,813 members
Articles / Programming Languages / C#
Posted 25 Jan 2012

Tagged as


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.

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.


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


About the Author

Andrew Rissing
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 
I'd have to agree with your comment. The big bottleneck slowing everything down is the dynamic keyword.By about 100ms. I was getting far better times than the lambda purely because, I was initialising the call to GetContructor() in my class's constructor. Only then i was doing the test on the call to NewInstance(). Thus, the times were in favor of the DynamicMethod approach. However the winner is the lamda. My DynamicMethod: 171ms, Lambda: 137ms
GeneralI am aware of this alternative. However my results where wel... Pin
Dean Oliver25-Jan-12 9:44
MemberDean Oliver25-Jan-12 9:44 
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.