CSharp - 在通用序列创建器上,为什么使用函数 <> 比使用 new() 约束要快得多

  显示原文与译文双语对照的内容
0 0

请考虑下面的代码。。。

放到我来测试RELEASE,( 不是调试) x86一门Windows 7 x64 PC ( Intel i7 3GHz ) 而获得以下结果:

CreateSequence() with new() took 00:00:00.9158071
CreateSequence() with creator() took 00:00:00.1383482
CreateSequence() with new() took 00:00:00.9198317
CreateSequence() with creator() took 00:00:00.1372920
CreateSequence() with new() took 00:00:00.9340462
CreateSequence() with creator() took 00:00:00.1447375
CreateSequence() with new() took 00:00:00.9344077
CreateSequence() with creator() took 00:00:00.1365162

似乎使用Func<>定义委托来创建新对象超过6 倍调用" new T( ) 直接" 。

我觉得稍微有点意外。。。 我猜是因为一些内联通过Jitter,但我能想到它有可能已经优化" 新T( ) " 也不错。

你们谁有变量的说明?

也许我做一些错误。 ( 我已经考虑这个影响垃圾回收器可能有,但重新排列代码和增加GC .Collect( ) 等) 不会更改结果显著) 。

不管怎样,下面是代码:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            int repeats =    100;
            int count   = 100000;
            for (int outer = 0; outer < 4; ++outer)
            {
                sw.Restart();
                for (int inner = 0; inner < repeats; ++inner)
                {
                    CreateSequence<object>(count).Count();
                }
                Console.WriteLine("CreateSequence() with new() took " + sw.Elapsed);
                sw.Restart();
                for (int inner = 0; inner < repeats; ++inner)
                {
                    CreateSequence(count, () => new object()).Count();
                }
                Console.WriteLine("CreateSequence() with creator() took " + sw.Elapsed);
                Console.WriteLine();
            }
        }
        public static IEnumerable<T> CreateSequence<T>(int n) where T: new()
        {
            for (int i = 0; i < n; ++i)
            {
                yield return new T();
            }
        }
        public static IEnumerable<T> CreateSequence<T>(int n, Func<T> creator)
        {
            for (int i = 0; i < n; ++i)
            {
                yield return creator();
            }
        }
    }
}
时间:原作者:3个回答

0 0

new()约束只保证传入的类型具有无参数构造函数。 如果你真的调用 new T()( 以及任何类型变量的名称),它实际执行这个:

Activator.CreateInstance<T>();

其中,它的核心使用反射。

原作者:
...