13

考虑以下代码...

在我对 Windows 7 x64 PC(Intel i7 3GHz)上的 RELEASE(不是调试!)x86 构建的测试中,我获得了以下结果:

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<> 定义委托来创建新对象比直接调用“new T()”快 6 倍以上。

我觉得这有点出乎意料......我猜这是因为 Jitter 做了一些内联,但我原以为它也能够优化“new 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();
            }
        }
    }
}
4

1 回答 1

14

new()约束只确保传入的类型具有无参数构造函数。如果您实际调用new T()(或无论您的类型参数的名称是什么),它实际上会这样做:

Activator.CreateInstance<T>();

其核心是使用反射。

于 2012-04-16T12:34:14.750 回答