When you have code like the following:
static T GenericConstruct() where T : new()
{
return new T();
}
The C# compiler insist
This is a little bit faster, since the expression is only compiled once:
public class Foo where T : new()
{
static Expression> x = () => new T();
static Func f = x.Compile();
public static T build()
{
return f();
}
}
Analyzing the performance, this method is just as fast as the more verbose compiled expression and much, much faster than new T() (160 times faster on my test PC) .
For a tiny bit better performance, the build method call can be eliminated and the functor can be returned instead, which the client could cache and call directly.
public static Func BuildFn { get { return f; } }