Click here to Skip to main content
12,350,143 members (27,227 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

8.5K views
3 bookmarked
Posted

Alternative to Activator.CreateInstance

, 26 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Andrew Rissing
Software Developer (Senior)
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.

You may also be interested in...

Comments and Discussions

 
GeneralReason for my vote of 1 No DM or Expressions are needed for ... Pin
nonexisto26-Jan-12 2:15
membernonexisto26-Jan-12 2:15 
GeneralRe: Corrected. I removed the type constraint. I didn't realize... Pin
Andrew Rissing26-Jan-12 3:39
memberAndrew Rissing26-Jan-12 3:39 
GeneralI'd have to agree with your comment. The big bottleneck slow... Pin
Dean Oliver25-Jan-12 18:40
memberDean Oliver25-Jan-12 18:40 
GeneralI am aware of this alternative. However my results where wel... Pin
Dean Oliver25-Jan-12 8:44
memberDean Oliver25-Jan-12 8:44 
GeneralRe: The overhead in your method may likely be due to the dynamic... Pin
Andrew Rissing25-Jan-12 9:36
memberAndrew Rissing25-Jan-12 9: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.

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