我正在优化我的代码,并且我注意到使用属性(甚至是自动属性)对执行时间有着深远的影响。看下面的例子:使用属性和性能
[Test]
public void GetterVsField()
{
PropertyTest propertyTest = new PropertyTest();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
propertyTest.LoopUsingCopy();
Console.WriteLine("Using copy: " + stopwatch.ElapsedMilliseconds/1000.0);
stopwatch.Restart();
propertyTest.LoopUsingGetter();
Console.WriteLine("Using getter: " + stopwatch.ElapsedMilliseconds/1000.0);
stopwatch.Restart();
propertyTest.LoopUsingField();
Console.WriteLine("Using field: " + stopwatch.ElapsedMilliseconds/1000.0);
}
public class PropertyTest
{
public PropertyTest()
{
NumRepet = 100000000;
_numRepet = NumRepet;
}
int NumRepet { get; set; }
private int _numRepet;
public int LoopUsingGetter()
{
int dummy = 314;
for (int i = 0; i < NumRepet; i++)
{
dummy++;
}
return dummy;
}
public int LoopUsingCopy()
{
int numRepetCopy = NumRepet;
int dummy = 314;
for (int i = 0; i < numRepetCopy; i++)
{
dummy++;
}
return dummy;
}
public int LoopUsingField()
{
int dummy = 314;
for (int i = 0; i < _numRepet; i++)
{
dummy++;
}
return dummy;
}
}
在Release
模式我的机器上我得到:
Using copy: 0.029
Using getter: 0.054
Using field: 0.026
这在我的情况是一场灾难 - 最关键的循环,如果我想只是不能使用任何属性以获得最大的性能。
我在做什么错在这里?我在想这些是JIT optimizer
的inlined
。
当你说“在发布模式下”你是指release * build *配置,还是在没有调试器的情况下运行?如果你在调试器中运行,我完全希望看到一个重大的打击。还要注意,一个循环很不寻常,因为这个循环很紧张......并且合理地微调优化*仅仅是那些被证明是瓶颈的应用程序部分。 –
我刚刚测试了自己的代码,x86 JIT使属性访问与字段访问基本相同。 x64 JIT显示了你在问题中的行为。您可能想尝试即将推出的新x64 JIT:http://blogs.msdn.com/b/dotnet/archive/2014/02/27/ryujit-ctp2-getting-ready-for-prime- time.aspx –
@JonSkeet,我的意思是发布版本配置。我从ReSharper测试跑步者那里运行这些测试是精确的。 – Grzenio