9

我正在阅读有关 java 编译器如何在可能的情况下将与“+”运算符连接的字符串编译为 StringBuilder 的实例,以及如何更好地使用简单的“+”运算符,因为它们编译为相同的代码。(除非您在 while 循环中构建字符串,在这种情况下,显然最好使用 StringBuilder。)

我还读到字符串上的 .concat 方法一直是最糟糕的选择(以至于它被Findbugs变成了一个错误!)。

所以我决定自己在eclipse中编写一个小java类来测试它。我的结果让我有点吃惊。我发现,如果我在 Eclipse 和命令行中编译并运行它们,不同的方法相对更快或更慢。

首先我的日食结果是:

the total millis to concatenate with + was: 12154
the total millis to concatenate with .concat was: 8840
the total millis to concatenate with StringBuilder was: 11350
the total millis to concatenate with StringBuilder with a specified size was: 5611

所以在eclipse中指定大小的StringBuilder最快,其次是.concat(奇怪),然后StringBuilder和“+”连接几乎相同。

然而,我在命令行上的结果是:

the total millis to concatenate with + was: 4139
the total millis to concatenate with .concat was: 8590
the total millis to concatenate with StringBuilder was: 10888
the total millis to concatenate with StringBuilder with a specified size was: 6033

因此,当我从命令行编译并运行时,“+”运算符显然是最快的,其次是带有大小的 String builder,然后是 concat,最后是普通的 StringBuilder!

这对我来说没有意义。显然,我读到的所有 stackoverflow 答案都说 + 运算符编译成普通的旧 StringBuilder 实例必须是过时的。

有谁知道这里到底发生了什么?

我正在使用 jdk1.7.0_07,据我所知,eclipse 和我的命令行都引用了完全相同的一个。我知道的唯一区别是 eclipse 是使用“javaw”,但从我读过的内容来看,这不应该有所作为。

如果您想验证我没有做错任何事情,这是我的测试课程,但我很确定它是可靠的。

public class Test {

    static final int LOOPS = 100000000;
    static final String FIRST_STRING = "This is such";
    static final String SECOND_STRING = " an awesomely cool ";
    static final String THIRD_STRING = "to write string.";

    /**
     * @param args
     */
    public static void main(String[] args) {

        Test.plusOperator();
        Test.dotConcat();
        Test.stringBuilder();
        Test.stringBuilderSizeSpecified();

    }

    public static void plusOperator() {
        String localOne = FIRST_STRING;
        String localTwo = SECOND_STRING;
        String localThree = THIRD_STRING;

        Calendar startTime = Calendar.getInstance();
        for (int x = 0; x < LOOPS; x++) {
            String toPrint = localOne + localTwo + localThree;
        }
        Calendar endTime = Calendar.getInstance();
        System.out.println("the total millis to concatenate with + was: " + 
                (endTime.getTimeInMillis() - startTime.getTimeInMillis()));
    }

    public static void stringBuilder() {
        String localOne = FIRST_STRING;
        String localTwo = SECOND_STRING;
        String localThree = THIRD_STRING;

        Calendar startTime = Calendar.getInstance();
        for (int x = 0; x < LOOPS; x++) {
            StringBuilder toBuild = new StringBuilder()
                .append(localOne)
                .append(localTwo)
                .append(localThree);
        }
        Calendar endTime = Calendar.getInstance();
        System.out.println("the total millis to concatenate with StringBuilder was: " + 
                (endTime.getTimeInMillis() - startTime.getTimeInMillis()));
    }

    public static void stringBuilderSizeSpecified() {
        String localOne = FIRST_STRING;
        String localTwo = SECOND_STRING;
        String localThree = THIRD_STRING;

        Calendar startTime = Calendar.getInstance();
        for (int x = 0; x < LOOPS; x++) {
            StringBuilder toBuild = new StringBuilder(50)
                .append(localOne)
                .append(localTwo)
                .append(localThree);
        }
        Calendar endTime = Calendar.getInstance();
        System.out.println("the total millis to concatenate with StringBuilder with a specified size was: " + 
                (endTime.getTimeInMillis() - startTime.getTimeInMillis()));
    }

    public static void dotConcat() {
        String localOne = FIRST_STRING;
        String localTwo = SECOND_STRING;
        String localThree = THIRD_STRING;

        Calendar startTime = Calendar.getInstance();
        for (int x = 0; x < LOOPS; x++) {
            String toPrint = localOne.concat(localTwo).concat(localThree);
        }
        Calendar endTime = Calendar.getInstance();
        System.out.println("the total millis to concatenate with .concat was: " + 
                (endTime.getTimeInMillis() - startTime.getTimeInMillis()));
    }

}
4

2 回答 2

12

在 Oracle JDK 1.7 (javac 1.7.0_17) 上,“+”运算符仍然使用 实现StringBuilder,如javap -c在类上运行以获取字节码所示(此处仅显示循环):

public static void plusOperator();
Code:

  16: iload         4
  18: ldc           #10                 // int 100000000
  20: if_icmpge     53
  23: new           #11                 // class java/lang/StringBuilder
  26: dup           
  27: invokespecial #12                 // Method java/lang/StringBuilder."<init>":()V
  30: aload_0       
  31: invokevirtual #13                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  34: aload_1       
  35: invokevirtual #13                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  38: aload_2       
  39: invokevirtual #13                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  42: invokevirtual #14                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
  45: astore        5
  47: iinc          4, 1
  50: goto          16


public static void stringBuilder();
Code:

  16: iload         4
  18: ldc           #10                 // int 100000000
  20: if_icmpge     50
  23: new           #11                 // class java/lang/StringBuilder
  26: dup           
  27: invokespecial #12                 // Method java/lang/StringBuilder."<init>":()V
  30: aload_0       
  31: invokevirtual #13                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  34: aload_1       
  35: invokevirtual #13                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  38: aload_2       
  39: invokevirtual #13                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  42: astore        5
  44: iinc          4, 1
  47: goto          16

这两者之间的唯一区别是带有“+”的版本将循环内的转换StringBuilder为a 。String

所以问题就变成了:为什么你的测试对相同的代码显示出如此不同的结果。或者更完整地说,为什么这不是一个有效的微基准。以下是一些可能的原因:

  • 你在计算挂钟时间。这意味着您实际上是在测量 JVM 在运行测试时所做的一切。其中包括垃圾收集(这很重要,因为您正在创建大量垃圾)。您可以通过获取线程 CPU 时间来缓解这种情况。
  • 您无需验证 HotSpot 何时或是否正在编译方法。这就是为什么您应该在任何微基准测试之前进行预热阶段:基本上,main()在运行实际测试之前运行多次。
于 2013-03-13T22:31:31.287 回答
1

尝试放置StringBuilder toBuild = new StringBuilder()在循环上方。String toPrint与字符串相同+=,你会看到不同之处。
不要在循环中创建新的 String 和 StringBuilder。

于 2013-03-13T22:27:15.320 回答