Java:String 與 StringBuffer 效能比較

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

JDK Version: 1.8

跑出來的結果如下:

StringBuffer object 1455 milliseconds.
String object with string literal 9 milliseconds.
String object with String construtor 160 milliseconds.
String +operator 2448 milliseconds.
StringBuffer append method 2 milliseconds.

建立 StringBuffer object 會花比較多的時間,但StringBuffer在串聯字串時的效能遠比String 還快很多,另外還有個StringBuilder可用,詳細的比較內容可參考下列網址:

本文中的測試程式碼:

public classStringVersusStringBuffer {

   public static void main(String args[]) {
      int ROUNDS = 20000000;
      long startMS, stopMS, elapsedMS;

      startMS = System.currentTimeMillis();
      for(int i = 0; i < ROUNDS; i++) {
          StringBuffer strBuffer = new StringBuffer("Hello");
      }

      stopMS = System.currentTimeMillis();
      elapsedMS = stopMS - startMS;

      System.out.println("Time for creating StringBuffer object:" + elapsedMS);

      startMS = System.currentTimeMillis();
      for(int i = 0; i < ROUNDS; i++) {
          String str = "Hello";
      }

      stopMS = System.currentTimeMillis();
      elapsedMS = stopMS - startMS;
     
      System.out.println("Time for creating String object with string literal:" + elapsedMS);
     
      startMS = System.currentTimeMillis();
      for(int i = 0; i < ROUNDS; i++) {
          String str = new String("Hello"); 
      }

      stopMS = System.currentTimeMillis();
      elapsedMS = stopMS - startMS;

      System.out.println("Time for creating String object with String construtor:" + elapsedMS);
     
      String helloStr = "Hello";
      StringBuffer helloStrBuffer = new StringBuffer("Hello");
     
      ROUNDS = 20000;
     
      startMS = System.currentTimeMillis();
      for(int i = 0; i < ROUNDS; i++) {
          helloStr += "Hello";
      }

      stopMS = System.currentTimeMillis();
      elapsedMS = stopMS - startMS;

      System.out.println("Time for String +operator:" + elapsedMS);
     
      startMS = System.currentTimeMillis();
      for(int i = 0; i < ROUNDS; i++) {
          helloStrBuffer.append("Hello");
      }

      stopMS = System.currentTimeMillis();
      elapsedMS = stopMS - startMS;

      System.out.println("Time for StringBuffer append method:" + elapsedMS);
   }

}


沒有留言: