看起来你在这里真正做的是比较手动拳击和内置拳击。内置拳击已经过高度优化 - 所以我不希望在这里看到巨大的差异,但我们可以检查一下。重要的是,请注意两者具有相同的内存影响:一个堆对象包含一个int
字段,每个int
装箱/包装。
以下显示了两个接近的时间几乎相同;因此,我会说,只需以直接/内置方式将其装箱即可。
注意:在发布模式下运行它,没有调试器(最好在命令行)。请注意,第一次调用是为了预先 JIT 一切。
using System;
using System.Diagnostics;
public sealed class IntObj
{
public readonly int Value;
public IntObj(int value)
{
Value = value;
}
}
static class Program
{
static void Main()
{
Run(1, 0, false);
Run(100000, 500, true);
Console.ReadKey();
}
static void Run(int length, int repeat, bool report)
{
var data = new object[length];
int chk = 0;
var watch = Stopwatch.StartNew();
for (int j = 0; j < repeat; j++)
{
for (int i = 0; i < data.Length; i++)
{
data[i] = i;
chk += i;
}
}
watch.Stop();
if(report) Console.WriteLine("Box: {0}ms (chk: {1})", watch.ElapsedMilliseconds, chk);
chk = 0;
watch = Stopwatch.StartNew();
for (int j = 0; j < repeat; j++)
{
for (int i = 0; i < data.Length; i++)
{
chk += (int) data[i];
}
}
watch.Stop();
if (report) Console.WriteLine("Unbox: {0}ms (chk: {1})", watch.ElapsedMilliseconds, chk);
chk = 0;
watch = Stopwatch.StartNew();
for (int j = 0; j < repeat; j++)
{
for (int i = 0; i < data.Length; i++)
{
data[i] = new IntObj(i);
chk += i;
}
}
watch.Stop();
if (report) Console.WriteLine("Wrap: {0}ms (chk: {1})", watch.ElapsedMilliseconds, chk);
chk = 0;
watch = Stopwatch.StartNew();
for (int j = 0; j < repeat; j++)
{
for (int i = 0; i < data.Length; i++)
{
chk += ((IntObj)data[i]).Value;
}
}
watch.Stop();
if (report) Console.WriteLine("Unwrap: {0}ms (chk: {1})", watch.ElapsedMilliseconds, chk);
}
}