【发布时间】:2013-12-03 02:35:36
【问题描述】:
可能是我的硬件是罪魁祸首,但在测试过程中,我发现:
void SomeFunction(AType ofThing) {
DoSomething(ofThing);
}
...比:
private AType _ofThing;
void SomeFunction() {
DoSomething(_ofThing);
}
我认为这与编译器如何将其转换为 CIL 有关。谁能具体解释一下为什么会这样?
这里有一些代码:
public void TestMethod1()
{
var stopwatch = new Stopwatch();
var r = new int[] { 1, 2, 3, 4, 5 };
var i = 0;
stopwatch.Start();
while (i < 1000000)
{
DoSomething(r);
i++;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
i = 0;
stopwatch.Restart();
while (i < 1000000)
{
DoSomething();
i++;
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
private void DoSomething(int[] arg1)
{
var r = arg1[0] * arg1[1] * arg1[2] * arg1[3] * arg1[4];
}
private int[] _arg1 = new [] { 1, 2, 3, 4, 5 };
private void DoSomething()
{
var r = _arg1[0] * _arg1[1] * _arg1[2] * _arg1[3] * _arg1[4];
}
在我的情况下,使用私有财产要慢 2.5 倍。
【问题讨论】:
-
你能证明它更快吗?你是怎么测试的?
-
可能它已经在 CPU 缓存中,因为它已经从内存中加载了。而提到一个成员,你必须从记忆中引入它。
-
@Charleh 我使用了秒表,运行了几百万次,从我当前的项目中获得了两个对象的纳秒时间。将进行另一次测试以共享代码。
-
@MoslemBenDhaou 不一定要实用,他可能只是对 C# 在幕后的工作方式感兴趣。
-
@MoslemBenDhaou 我认为他应该关心,直到他不必关心。对系统如何工作的任何检查都会增加人们对它的理解。
标签: c# performance cil