位置:首頁 > Java技術 > java實例教學 > 連接字符串-Java實例

連接字符串-Java實例

如何優化字符串連接?

解決方法

下麵的例子顯示了通過使用“+”操作符和StringBuffer.append()方法拚接的性能。

public class StringConcatenate{
   public static void main(String[] args){
      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)+ " ms");
      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");
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("Time taken for String concatenation" 
      + "using StringBuffer : "
      + (endTime1 - startTime1)+ " ms");
   }
}

結果

上麵的代碼示例將產生以下結果。結果可能會不同。

Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 22 ms