如何在 Java 中比較字串建立的效能



問題描述

如何比較字串建立的效能?

解決方案

以下示例比較了以兩種不同方式建立的兩個字串的效能。

public class StringComparePerformance {
   public static void main(String[] args) {      
      long startTime = System.currentTimeMillis();
      
      for(int i = 0; i < 50000; i++) {
         String s1 = "hello";
         String s2 = "hello"; 
      }
      long endTime = System.currentTimeMillis();
      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 s3 = new String("hello");
         String s4 = new String("hello");
      }
      long endTime1 = System.currentTimeMillis();
      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 : 16 milli seconds
java_strings.htm
廣告
© . All rights reserved.