程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> A+=B和A=A+B真的有區別嗎?

A+=B和A=A+B真的有區別嗎?

編輯:C#入門知識

今天看到一篇文章,是關於在.NET中如何提升程序性能的,裡面有這樣一條:

建議使用+=、-= 等簡化操作符
例如原有表達式 A=A+B
改為A+=B
這樣不僅減少了敲入代碼的數量,而且由於變量A只出現一次,在運行時也提高了系統的性能。

確實這樣的操作能減少輸入,但是對於是否真能提高性能,以及以什麼方式來提高性能(是優化了代碼還是節省了空間等),確實不太知道,帶著好奇心,自己動手試試了。首先寫了兩個測試方法:

      static void test1()   

{
string A = "string A";
string B = "string B";
A += B;
}

static void test2()
{
string A = "string A";
string B = "string B";
A = A + B;
}

編譯後用ildasm查看兩者的IL,可以看出,兩個方法的IL是一致的:

.maxstack  2   
.locals init ([0] string A,
[1] string B)
IL_0000: nop
IL_0001: ldstr "string A"
IL_0006: stloc.0
IL_0007: ldstr "string B"
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: call string [mscorlib]System.String::Concat(string,
string)
IL_0014: stloc.0
IL_0015: ret

既然IL都是完全一樣的,想必用reflector反編譯後的代碼也是一樣的喽。

這裡分別按優化級別來查看:

//優化級別為NONE

private static void test1()//或者test2
{
string A;
string B;
A = "string A";
B = "string B";
A = A + B;
return;
}//優化級別為.NET 3.5private static void test1()()//或者test2

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved