Java 编译器是否包含字符串常量折叠?
我发现 Java 支持原始类型的常量折叠,但是 String
s 呢?
I found out that Java supports constant folding of primitive types, but what about String
s?
示例
如果我创建以下源代码
out.write(""
+ "<markup>"
+ "<nested>"
+ "Easier to read if it is split into multiple lines"
+ "</nested>"
+ "</markup>"
+ "");
编译后的代码中有什么内容?
What goes into the compiled code?
组合版本?out.write("<markup><nested>如果分成多行更容易阅读</nested></markup>");
还是效率较低的运行时串联版本?out.write(new StringBuilder("").append("<markup>").append("<nested>").append("拆分成多行更容易阅读").append("</nested>").append("</markup>").append(""));
Or the less efficient run-time concatenation version? out.write(new StringBuilder("").append("<markup>").append("<nested>").append("Easier to read if it is split into multiple lines").append("</nested>").append("</markup>").append(""));
推荐答案
这是一个简单的测试:
public static void main(final String[] args) {
final String a = "1" + "2";
final String b = "12";
System.out.println(a == b);
}
输出:
true
所以,是的,编译器会折叠.
So, yes, the compiler will fold.
相关文章