Java 编译器是否包含字符串常量折叠? [英] Does Java Compiler include String Constant Folding?

查看:36
本文介绍了Java 编译器是否包含字符串常量折叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Java 支持原始类型的常量折叠,但是 Strings 呢?

I found out that Java supports constant folding of primitive types, but what about Strings?

示例

如果我创建以下源代码

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.

这篇关于Java 编译器是否包含字符串常量折叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆