【发布时间】:2017-07-25 09:15:02
【问题描述】:
为什么用构造函数创建结构比直接赋值慢? 在下面的代码中,我得到 10 秒的自定义构造函数和 6 秒没有!纯循环需要5秒。自定义构造函数比直接访问慢五 (!sic) 倍。
有什么技巧可以加快自定义构造函数的速度吗?
class Program
{
public struct Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
for(int i =0; i < int.MaxValue; i++)
{
var a = new Point(i, i);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < int.MaxValue; i++)
{
var a = new Point();
a.x = i;
a.y = i;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
【问题讨论】:
-
你的分析是错误的。它不是慢 5 倍。您必须除以 int.MaxValue 才能进行高于相对速度的比较。构造函数调用您的自定义构造函数 Point() 方法,这需要额外的时间。调用应该非常小,但当 int.MaxValue 非常大时可能需要几秒钟。
-
这些结果可能完全被 GC 时间扭曲了。尝试交换两个循环,看看会得到什么结果。
-
还要确保您正在测试发布版本,并且您没有在调试器中运行它。
-
简单循环需要 5 秒。使用自定义构造函数循环 10 秒。没有自定义构造函数的循环 6 秒。性能 = (10 - 5)/(6-5) ?
标签: c# struct constructor