如何比較字串創建的性能?

在Java中,如何比較字串創建的性能?

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

package com.zaixian;

public class StringComparePerformance {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 50000; i++) {
            String s1 = "This is a String";
            String s2 = "This is a String";
        }
        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("This is a String");
            String s4 = new String("This is a String");
        }
        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字串 下一篇: Java數組