When you have code like the following:
static T GenericConstruct<T>() where T : new()
{
return new T();
}
The C# compiler insists on emitting a call to Activator.CreateInstance, which is considerably slower than a native constructor.
I have the following workaround:
public static class ParameterlessConstructor<T>
where T : new()
{
public static T Create()
{
return _func();
}
private static Func<T> CreateFunc()
{
return Expression.Lambda<Func<T>>( Expression.New( typeof( T ) ) ).Compile();
}
private static Func<T> _func = CreateFunc();
}
// Example:
// Foo foo = ParameterlessConstructor<Foo>.Create();
But it doesn't make sense to me why this workaround should be necessary.
Activator::CreateInstance
call for general,class
andstructure
constraints. – Compensation