字串駐留備忘

2022-02-10 17:18:32 字數 1292 閱讀 4184

下面是個人的練習:

**//

字串拘留練習 by mcjeremy

//宣告s1時,拘留池中沒有該字串,因此將它放進去

//放進去後,string.isintered(s1),將返回該字串值

string

s1 =

"abc123";

//宣告s2時,由於拘留池中已經有該字串存在,因此不再分配記憶體

//s2和s1將指向同乙個引用

string

s2 =

"abc123";

//s3背後實際呼叫的是concat,因此,它是動態建立的。

//因此,會分配新的記憶體

string

s3 =

s1 +

s2;//

建立s4時,編譯器會優化它,背後呼叫的是ldstr,因此,會發現拘留池中已經

//有abc123,因此不再分配記憶體,此時 s1,s2,s4都指向同乙個引用

string

s4 =

"abc"+

"123";

string

s5 =

"123";

//建立s6時,背後實際呼叫的是concat,因此,它是動態建立的。

//因此,會分配新的記憶體

string

s6 =

"abc"+

s5;console.writeline(object.referenceequals(s1, s2)); 

//true

console.writeline(object.referenceequals(s1, s3));

//false

console.writeline(object.referenceequals(s1, s4));

//true

console.writeline(object.referenceequals(s1,s6)); 

//false

console.writeline(

string

.isinterned(s3) ??"

null

"); 

//null

console.writeline(

string

.isinterned(s1) ??"

null

"); 

//abc123

console.writeline(

string

.isinterned(s6) ??"

null

"); 

//abc123

關於字串駐留

首先看幾個例子 示例1 static void main 示例2 static void main 示例3 public const string s1 abc static void main 示例4 public static string s1 abc static void main 示例1...

C 中字串駐留技術

msdn概念 公共語言執行庫通過維護乙個表來存放字串,該錶稱為拘留池,它包含程式中以程式設計方式宣告或建立的每個唯一的字串的乙個引用。因此,具有特定值的字串的例項在系統中只有乙個。上面的概念不好理解,我們還是從基礎說起 一 眾所周知,c 中的string是乙個引用型別,string物件存放在堆上,而...

Python隱藏特性 字串駐留 常量摺疊

下面是python字串的一些微妙的特性,絕對會讓你大吃一驚。案例一 a some string id a 140420665652016 id some string 注意兩個的id值是相同的.140420665652016案例二 a wtf b wtf a is b true a wtf b wt...