Dot-Net

字元串不變性

  • March 9, 2018

字元串不變性是通過語句起作用,還是通過語句中的字元串起作用?

例如,我了解以下程式碼將在堆上分配兩個字元串。

string s = "hello ";
s += "world!";

“hello” 將保留在堆上,直到垃圾收集;並且 s 現在引用“hello world!” 在堆上。但是,以下行在堆上分配了多少個字元串…1 或 2?另外,是否有工具/方法來驗證結果?

string s = "goodbye " + "cruel world!";

編譯器對字元串連接有特殊處理,這就是為什麼第二個例子只有一個字元串。而“實習”意味著即使你執行這條線 20000 次,仍然只有 1 個字元串。

重新測試結果……最簡單的方法(在這種情況下)可能是查看反射器:

.method private hidebysig static void Main() cil managed
{
   .entrypoint
   .maxstack 1
   .locals init (
       [0] string s)
   L_0000: ldstr "goodbye cruel world!"
   L_0005: stloc.0 
   L_0006: ldloc.0 
   L_0007: call void [mscorlib]System.Console::WriteLine(string)
   L_000c: ret 
}

如您所見 ( ldstr),編譯器已經為您完成了這項工作。

引用自:https://stackoverflow.com/questions/372354