java基础-javac之神奇的编译优化(待续)

聪明的编译器

开始学java时,脑边总是有这些概念程序不能像下面这样写:

1
2
3
4
5
6
7
8
9
public class ConcatString {
public static void main(String[] args) {
concatString("a", "v", "v");
}
public static String concatString(String a, String b, String c) {
return a + b + c;
}
}

这样会产生大量新的String对象。今天偶然看到《深入理解JVM》关于锁消除的一段话后(周老师是为了讲锁消除),反编译了一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$ javap -c ConcatString
警告: 二进制文件ConcatString包含string.ConcatString
Compiled from "ConcatString.java"
public class string.ConcatString {
public string.ConcatString();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2 // String a
2: ldc #3 // String v
4: ldc #3 // String v
6: invokestatic #4 // Method concatString:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
9: pop
10: return
public static java.lang.String concatString(java.lang.String, java.lang.String, java.lang.String);
Code:
0: new #5 // class java/lang/StringBuilder
3: dup
4: invokespecial #6 // Method java/lang/StringBuilder."<init>":()V
7: aload_0
8: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_1
12: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: aload_2
16: invokevirtual #7 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
22: areturn
}

可以看到编译器已经自动帮我们转成了StringBuilder的append方法来操作,真是操碎了心。

未完~后面会继续探索一些编译器为我们做的优化。

坚持原创技术分享,您的支持将鼓励我继续创作!

热评文章