Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Alternative to Activator.CreateInstance

By , 26 Jan 2012
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<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
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 ... Pinmembernonexisto26-Jan-12 2:15 
GeneralRe: Corrected. I removed the type constraint. I didn't realize... PinmemberAndrew Rissing26-Jan-12 3:39 
GeneralI'd have to agree with your comment. The big bottleneck slow... PinmemberDean Oliver25-Jan-12 18:40 
GeneralI am aware of this alternative. However my results where wel... PinmemberDean Oliver25-Jan-12 8:44 
GeneralRe: The overhead in your method may likely be due to the dynamic... PinmemberAndrew Rissing25-Jan-12 9:36 

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.

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