为什么一个泛型类型用new()约束调用新当C#编译器发出Activator.CreateInstance? [英] Why does the c# compiler emit Activator.CreateInstance when calling new in with a generic type with a new() constraint?

查看:157
本文介绍了为什么一个泛型类型用new()约束调用新当C#编译器发出Activator.CreateInstance?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你有code这样的:

When you have code like the following:

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

C#编译器坚持发射到Activator.CreateInstance的调用,这是不是本机的构造相当慢。

The C# compiler insists on emitting a call to Activator.CreateInstance, which is considerably slower than a native constructor.

我有以下解决方法:

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.

推荐答案

我的犯罪嫌疑人的这是一个JITting问题。目前,JIT重复使用相同的产生code对所有引用类型变量 - 这样一个列表&LT;串&GT; 的虚函数表指向同一台机器code作为该列表与LT的;流&gt; 。如果每个新T()呼叫曾在即时编译code,以解决这是行不通的。

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.

一个有趣的小点:在的没有的情况下,确实是值类型的参数的构造函数被调用,如果有一个(这是微乎其微罕见)。请参阅我最近的博客文章细节。我不知道是否有强迫它在EX pression树木的任何方式。

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.

这篇关于为什么一个泛型类型用new()约束调用新当C#编译器发出Activator.CreateInstance?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆