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

后端 未结 5 1525
太阳男子
太阳男子 2020-11-27 06:33

When you have code like the following:

static T GenericConstruct() where T : new()
{
    return new T();
}

The C# compiler insist

5条回答
  •  长情又很酷
    2020-11-27 07:07

    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; } }
    

提交回复
热议问题