String的創建
String s = “hello”;
JVM先根據內容”hello”查找對象,如果沒有找到,則在heap上創建新對象,並將其賦予s1,否則使用已經存在的對象
String s = new String(“hello”);
JVM直接在heap上創建新的對象,所以在heap中會出現內容相同,地址不同的String對象
String的比較
”==” 比較地址
”equals” 比較內容
舉例:
String s1 = “hello”;
String s2 = “hello”;
String s3 = new String(“hello”);
s1 == s2; // true 地址相同
s1 == s3; // false 地址不同
s1.equals(s2); // true 內容相同
s1.equals(s3); // true 內容相同
intern() 方法
查找內容相同(equals())的字符串
String s1 = “hello”; // hello不存在,jvm創建新對象 (1)
String s2 = new String(“hello”); // 創舉新對象 (2),這時heap中存在兩個內容為hello的對象
s1 == s2; // false // 地址不同
s1.equals(s2); // true // 內容相同
s2 = s2.intern(); // true // 找到對象(1) 並賦予s2
s1 == s2; // true !! // 註意:此時s1,s2同指向(1)
效率:String 與 StringBuffer
情景1:
(1) String result = “hello” + ” world”;
(2) StringBuffer result = new String().append(“hello”).append(” world”);
(1) 的效率好於 (2),不要奇怪,這是因為JVM會做如下處理
編譯前 String result = “hello” + ” world”;
編譯後 String result = “hello world”;
情景2:
(1) public String getString(String s1, String s2) {
return s1 + s2;
}
(2) public String getString(String s1, String s2) {
return new StringBuffer().append(s1).append(s2);
}
(1) 的效率與 (2) 一樣,這是因為JVM會做如下處理
編譯前 return s1 + s2;
編譯後 return new StringBuffer().append(s1).append(s2);
情景3:
(1) String s = “s1”;
s += “s2”;
s += “s3”;
(2) StringBuffer s = new StringBuffer().append(“s1”).append(“s2”).append(“s3”);
(2) 的效率好於(1),因為String是不可變對象,每次”+=”操作都會造成構造新的String對象
情景4:
(1) StringBuffer s = new StringBuffer();
for (int i = 0; i < 50000; i ++) {
s.append(“hello”);
}
(2) StringBuffer s = new StringBuffer(250000);
for (int i = 0; i < 50000; i ++) {
s.append(“hello”);
}
(2) 的效率好於 (1),因為StringBuffer內部實現是char數組,默認初始化長度為16,每當字符串長度大於char
數組長度的時候,JVM會構造更大的新數組,並將原先的數組內容復制到新數組,(2)避免瞭復制數組的開銷
關鍵點
1). 簡單的認為 .append() 效率好於 “+” 是錯誤的!
2). 不要使用 new 創建 String
3). 註意 .intern() 的使用
4). 在編譯期能夠確定字符串值的情況下,使用”+”效率最高
5). 避免使用 “+=” 來構造字符串
6). 在聲明StringBuffer對象的時候,指定合適的capacity,不要使用默認值(18)
7). 註意以下二者的區別不一樣
- String s = “a” + “b”;
- String s = “a”;
s += “b”;