看起来你真的在这里做的是比较手动拳击和内置拳击。内置的拳击已经高度优化 - 所以我不希望在这里看到巨大的差异,但我们可以检查。重要的是,请注意两者都具有相同的内存影响:一个堆对象包含一个int
字段,每int
盒装/包装。
下面显示两个接近的相同时间;因此,我会说,把它直接/内置的方式。
注意:在发布模式下运行,没有调试器(理想情况下在命令行)。注意第一个电话是在那里预先处理所有事情。
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);
}
}
我还没有测量过,但我会说原始速度会更快。一个对象有开销。但在这种情况下,我认为可读性是一个更重要的措施。 Cpu周期比大脑周期便宜很多 –