String 之字串與記憶體管理

2021-07-16 01:13:33 字數 2161 閱讀 2161

github 的閱讀效果更佳

string a = new string("hello ")是建立物件的過程,string 物件建立過程與其他物件建立的過程大致相同。但是在階段,會從常量池中尋找 「hello」 常量,若成功找到,則複製乙份到堆中,構成 string 型別物件的一部分;否則,在堆中自行建立 「hello」 字串,用於對 string 類中的屬性進行賦值。

因此,無論怎麼樣,建立物件時,字串一定存在於堆中,a 引用的指向是堆中的字串,而不是常量池中的常量

string b = "hello "先建立乙個棧引用,然後從常量池中進行常量尋找(因為在 jvm 中,常量是一種資源,應當合理的重複使用),如果找到,則將引用指向它;否則,在常量池中建立新的常量 「hello」,然後進行引用指向。

final string a = "hello ";

final string b = "world";

string c = a + b;

上述**的執行過程為:

因為 a 與 b 都是常量,在編譯器中 a 就是 「hello」(同理,b 就是 「world」),兩者無論使用哪個都是指的乙個東西,所以在在編譯的時候(要注意,這時還沒有進行記憶體分配,字串常量池還沒有被初始化,所有的工作都停留在位元組碼層面)**變成了這樣:

final string a = "hello ";

final string b = "world";

string c = "hello" + "world";

拼接靜態字串的時候,編譯器通常要進行進行優化,對 c 中字串的拼接進行優化:

string c = "hello" + "world";

// 編譯器將視為

string c = "hello world";

最後,等到記憶體分配階段,字串常量池中會有:」hello」 「world」 「hello world」三個常量的存在。

final string constant_hello = "hello ";

final string constant_world = "world";

string var_hello = "hello ";

string concatenate_c = constant_hello + constant_world;

string concatenate_f = var_hello + constant_world;

system.out.println(concatenate_c == concatenate_f); // ?會相等嗎,false

為什麼 concatenate_c 和 concatenate_f 不相等呢?

我們知道,concatenate_c 在經過編譯器的處理與優化過後,會變成:

concatenate_c = "hello world";

原因是 constant_hello 和 constant_world 為常量,編譯器能夠認識他們。而 var_hello 並非常量,編譯器不認識它,所以會變成這樣:

string concatenate_f = var_hello + "world";
在記憶體分配的時候,才會得知 var_hello 的值,這時候不會再做靜態的拼接,而是進行動態的鏈結

concatenate_f -->

"hello " -->

"world"

concatenate_c == concatenate_f自然不成立了。

字串相等不想等(而非equals()),這是乙個很有意思的問題,既要考慮編譯器的優化,還要考慮字串記憶體的分配與管理

記憶體管理屬性字串

分類 ios開發 2014 05 26 14 36 726人閱讀收藏 舉報 assign 指定setter方法用簡單的賦值,這是預設操作。你可以對標量型別 如int 使用這個屬性。你可以想象乙個float,它不是乙個物件,所以它不能retain copy。assign指定setter方法用簡單的賦值...

精 (String)字串拼接記憶體解析

string str1 hello 字串常量池中沒有 hello 則建立乙個字串並把位址值返回給str1 string str2 hello 字串常量池中存在 hello 則創將該字串的位址值返回給str2 string str3 new string hello str3指向物件的位址,物件中的值...

Redis之String 字串型別

字串型別是redis中最為基礎的資料儲存型別,它在redis中是二進位制安全的,這便意味著該型別可以接受任何格式的資料,如jpeg影象資料或json物件描述資訊等。在redis中字串型別的value最多可以容納的資料長度是512m。命令原型 時間複雜度 命令描述 返回值o 1 追加後value的長度...