【发布时间】:2012-01-24 19:01:50
【问题描述】:
我发现Java supports constant folding of primitive types,但是Strings 呢?
示例
如果我创建以下源代码
out.write(""
+ "<markup>"
+ "<nested>"
+ "Easier to read if it is split into multiple lines"
+ "</nested>"
+ "</markup>"
+ "");
编译后的代码中有什么内容?
组合版本? out.write("<markup><nested>Easier to read if it is split into multiple lines</nested></markup>");
还是效率较低的运行时串联版本? out.write(new StringBuilder("").append("<markup>").append("<nested>").append("Easier to read if it is split into multiple lines").append("</nested>").append("</markup>").append(""));
【问题讨论】:
-
字符串连接比写入设备快大约 100 倍。如果没有(但确实如此),那真的没多大关系
-
我刚刚在我的笔记本电脑上测试了它,它慢了 50 倍。
-
这实际上是 JLS 要求的行为。 /
javap -c可以看到生成的代码。
标签: java string constants compiler-optimization constantfolding