时间:2010-07-23 19:07:43

标签: java string

6 个答案:

答案 0 :(得分:243)

答案 1 :(得分:80)

答案 2 :(得分:17)

答案 3 :(得分:14)

答案 4 :(得分:2)

答案 5 :(得分:2)

我写了一个可以测试性能的测试器类:

public class Tester
{
    public static void main(String[] args)
    {
        String text = "";

        int loopCount = 10000000;
        long startTime, endTime, duration1, duration2;

        startTime = System.nanoTime();
        for (int i = 0; i < loopCount; i++) {
            text.equals("");
        }
        endTime = System.nanoTime();
        duration1 = endTime - startTime;
        System.out.println(".equals(\"\") duration " +": \t" + duration1);

        startTime = System.nanoTime();
        for (int i = 0; i < loopCount; i++) {
            text.isEmpty();
        }
        endTime = System.nanoTime();
        duration2 = endTime - startTime;
        System.out.println(".isEmpty() duration "+": \t\t" + duration2);

        System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
    }
}

我发现使用.isEmpty()占用.equals(“”)的一半时间。