我正在優化我的代碼,並且我注意到使用屬性(甚至是自動屬性)對執行時間有着深遠的影響。看下面的例子:使用屬性和性能
[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