Why does the c# compiler emit Activator.CreateInstance when calling new in with a generic type with a new() constraint?

c#, constructor, generics, performance

Solution

I suspect it's a JITting problem. Currently, the JIT reuses the same generated code for all reference type arguments - so a `List<string>`'s vtable points to the same machine code as that of `List<Stream>`. That wouldn't work if each `new T()` call had to be resolved in the JITted code.

Just a guess, but it makes a certain amount of sense.

One interesting little point: in neither case does the parameterless constructor of a value type get called, if there is one (which is vanishingly rare). See my recent blog post for details. I don't know whether there's any way of forcing it in expression trees.

Problem

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.

Original source