連接字符串時候的優化技巧
你可以使用+操作符或者String.concat()或者StringBuffer.append()等辦法來連接多個字符串,那一種辦法具有最佳的性能呢?
如何作出選擇取決于兩種情景,第一種情景是需要連接的字符串是在編譯期決定的還是在運行期決定的,第二種情景是你使用的是 StringBuffer還是String。通常程序員會認為StringBuffer.append()方法會優于+操作符或 String.concat()方法,但是在一些特定的情況下這個假想是不成立的。
1) 第一種情景:編譯期決定相對于運行期決定
請看下面的StringTest3.java代碼和輸出結果。
package com.performance.string;
/** This class shows the time taken by string concatenation at compile time and run time.*/
public class StringTest3 {
public static void main(String[] args){
//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";
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken for string concatenation using + operator : "
+ (endTime - startTime)+ " milli seconds");
//Test the StringBuffer Concatination
文章來源于領測軟件測試網 http://www.kjueaiud.com/