創建字符串的較佳途徑
滯留字符串帶來的優化
連接字符串時的優化技巧
藉助StringBuffer的初始化過程的優化技巧
關鍵點
非可變對象一旦創建之後就不能再被改變,可變對象則可以在創建之後被改變。String對象是非可變對象,StringBuffer對象則是可變對象。爲獲得更佳的性能你需要根據實際情況小心謹慎地選擇到底使用這兩者中的某一個。下面的話題會作詳細的闡述。(注意:這個章節假設讀者已經具備Java的String和StringBuffer的相關基礎知識。)
1. String s1 = "hello";
String s2 = "hello";
2. String s3 = new String("hello");
String s4 = new String("hello");
StringTest1.java
* String literals and String objects.
*/
long startTime = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s2 = "hello";
}
System.out.println("Time taken for creation of String literals : "
+ (endTime - startTime) + " milli seconds" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s4 = new String("hello");
}
System.out.println("Time taken for creation of String objects : "
+ (endTime1 - startTime1)+" milli seconds");
}
}
這段代碼的輸出:
Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects : 170 milli seconds
Java虛擬機會維護一個內部的滯留字符串對象的列表(唯一字符串的池)來避免在堆內存中產生重複的String對象。當JVM從class文件里加載字符串字面量並執行的時候,它會先檢查一下當前的字符串是否已經存在於滯留字符串列表,如果已經存在,那就不會再創建一個新的String對象而是將引用指向已經存在的String對象,JVM會在內部爲字符串字面量作這種檢查,但並不會爲通過new關鍵字創建的String對象作這種檢查。當然你可以明確地使用String.intern()方法強制JVM爲通過new關鍵字創建的String對象作這樣的檢查。這樣可以強制JVM檢查內部列表而使用已有的String對象。
同一個字符串對象被重複地創建是不必要的,String.intern()方法可以避免這種情況。下圖說明了String.intern()方法是如何工作的,String.intern()方法檢查字符串對象的存在性,如果需要的字符串對象已經存在,那麼它會將引用指向已經存在的字符串對象而不是重新創建一個。下圖描繪了使用了intern()方法的字符串字面量和字符串對象的創建情況。
StringTest2.java
public class StringTest2 {
String variables[] = new String[50000];
for( int i=0;i<variables.length;i++){
variables[i] = "s"+i;
}
long startTime0 = System.currentTimeMillis();
for(int i=0;i<variables.length;i++){
variables[i] = "hello";
}
System.out.println("Time taken for creation of String literals : "
+ (endTime0 - startTime0) + " milli seconds" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<variables.length;i++){
variables[i] = new String("hello");
}
System.out.println("Time taken for creation of String objects with 'new' key word : "
+ (endTime1 - startTime1)+" milli seconds");
long startTime2 = System.currentTimeMillis();
for(int i=0;i<variables.length;i++){
variables[i] = new String("hello");
variables[i] = variables[i].intern();
}
System.out.println("Time taken for creation of String objects with intern(): "
+ (endTime2 - startTime2)+" milli seconds");
}
}
Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects with 'new' key word : 160 milli seconds
Time taken for creation of String objects with intern(): 60 milli seconds
你可以使用+操作符或者String.concat()或者StringBuffer.append()等辦法來連接多個字符串,那一種辦法具有最佳的性能呢?
請看下面的StringTest3.java代碼和輸出結果。
package com.performance.string;
public class StringTest3 {
//Test the String Concatination
long startTime = System.currentTimeMillis();
for(int i=0;i<5000;i++){
String result = "This is"+ "testing the"+ "difference"+ "between"+
"String"+ "and"+ "StringBuffer";
}
System.out.println("Time taken for string concatenation using + operator : "
+ (endTime - startTime)+ " milli seconds");
long startTime1 = System.currentTimeMillis();
for(int i=0;i<5000;i++){
StringBuffer result = new StringBuffer();
result.append("This is");
result.append("testing the");
result.append("difference");
result.append("between");
result.append("String");
result.append("and");
result.append("StringBuffer");
}
System.out.println("Time taken for String concatenation using StringBuffer : "
+ (endTime1 - startTime1)+ " milli seconds");
}
}
這是上面的代碼的輸出結果:
Time taken for String concatenation using + operator : 0 milli seconds
Time taken for String concatenation using StringBuffer : 50 milli seconds
很有趣地,+操作符居然比StringBuffer.append()方法要快,爲什麼呢?
String result = "This is"+"testing the"+"difference"+"between"+"String"+"and"+"StringBuffer";
編譯後:
String result = "This is testing the difference between String and StringBuffer";
這裏String對象在編譯期就決定了而StringBuffer對象是在運行期決定的。運行期決定需要額外的開銷當字符串的值無法預先知道的時候,編譯期決定作用於字符串的值可以預先知道的時候,下面是一個例子。
public String getString(String str1,String str2) {
return str1+str2;
}
編譯後:
return new StringBuffer().append(str1).append(str2).toString();
運行期決定需要更多的時間來運行。
看看下面的代碼你會發現與情景一相反的結果――連接多個字符串的時候StringBuffer要比String快。
StringTest4.java
using + operator and StringBuffer */
public class StringTest4 {
//Test the String Concatenation using + operator
long startTime = System.currentTimeMillis();
String result = "hello";
for(int i=0;i<1500;i++){
result += "hello";
}
System.out.println("Time taken for string concatenation using + operator : "
+ (endTime - startTime)+ " milli seconds");
long startTime1 = System.currentTimeMillis();
StringBuffer result1 = new StringBuffer("hello");
for(int i=0;i<1500;i++){
result1.append("hello");
}
System.out.println("Time taken for string concatenation using StringBuffer : "
+ (endTime1 - startTime1)+ " milli seconds");
}
}
這是上面的代碼的輸出結果:
Time taken for string concatenation using + operator : 280 milli seconds
Time taken for String concatenation using StringBuffer : 0 milli seconds
原因是兩者都是在運行期決定字符串對象,但是+操作符使用不同於StringBuffer.append()的規則通過String和StringBuffer來完成字符串連接操作。(譯註:什麼樣的規則呢?)
你可以通過StringBuffer的構造函數來設定它的初始化容量,這樣可以明顯地提升性能。這裏提到的構造函數是StringBuffer(int length),length參數表示當前的StringBuffer能保持的字符數量。你也可以使用ensureCapacity(int minimumcapacity)方法在StringBuffer對象創建之後設置它的容量。首先我們看看StringBuffer的缺省行爲,然後再找出一條更好的提升性能的途徑。
StringBuffer在內部維護一個字符數組,當你使用缺省的構造函數來創建StringBuffer對象的時候,因爲沒有設置初始化字符長度,StringBuffer的容量被初始化爲16個字符,也就是說缺省容量就是16個字符。當StringBuffer達到最大容量的時候,它會將自身容量增加到當前的2倍再加2,也就是(2*舊值+2)。
Time taken for String concatenation using StringBuffer with out setting size: 280 milli seconds
Time taken for String concatenation using StringBuffer with setting size: 0 milli seconds
1. 無論何時只要可能的話使用字符串字面量來常見字符串而不是使用new關鍵字來創建字符串。
2. 無論何時當你要使用new關鍵字來創建很多內容重複的字符串的話,請使用String.intern()方法。
3. +操作符會爲字符串連接提供最佳的性能――當字符串是在編譯期決定的時候。
4. 如果字符串在運行期決定,使用一個合適的初期容量值初始化的StringBuffer會爲字符串連接提供最佳的性能。