Java关于性能的变量声明之间的区别

时间:2015-12-17 17:58:01

标签: java

String s的这两种声明之间的区别在哪里:

1)

public static void main(String[] args) {
    String s;

    for (int i = 0; i < 1000000; i++) {
        s = "String" + i;
        System.out.println(s);
    }
}

2)

public static void main(String[] args) {
    for (int i = 0; i < 1000000; i++) {
        String s = "String" + i;
        System.out.println(s);
    }
}

我的任务经理说第一个不需要CPU和第二个。那么Java以两种不同的方式编译这两个样本?但是如何。

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

没有区别!

生成的字节码是相同的,除了以相反的顺序声明字段使得它们被分配不同的&#34;寄存器&#34;号。

命名两个方法test1test2,然后编译和反编译代码(使用javap -c),显示:

public static void test1();
  Code:
     0: iconst_0
     1: istore_1
     2: goto          32
     5: new           #22                 // class java/lang/StringBuilder
     8: dup
     9: ldc           #24                 // String String
    11: invokespecial #26                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
    14: iload_1
    15: invokevirtual #29                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
    18: invokevirtual #33                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    21: astore_0
    22: getstatic     #37                 // Field java/lang/System.out:Ljava/io/PrintStream;
    25: aload_0
    26: invokevirtual #43                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    29: iinc          1, 1
    32: iload_1
    33: ldc           #48                 // int 1000000
    35: if_icmplt     5
    38: return

public static void test2();
  Code:
     0: iconst_0
     1: istore_0
     2: goto          32
     5: new           #22                 // class java/lang/StringBuilder
     8: dup
     9: ldc           #24                 // String String
    11: invokespecial #26                 // Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
    14: iload_0
    15: invokevirtual #29                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
    18: invokevirtual #33                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    21: astore_1
    22: getstatic     #37                 // Field java/lang/System.out:Ljava/io/PrintStream;
    25: aload_1
    26: invokevirtual #43                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    29: iinc          0, 1
    32: iload_0
    33: ldc           #48                 // int 1000000
    35: if_icmplt     5
    38: return