简体   繁体   English

Java编译器字符串优化

[英]Java Compiler String optimization

It seems reasonable to me that the compiler is going to take something like this: 对我来说,编译器会采用这样的方式似乎是合理的:

log.info("A really long logger message that is kind of a pain in the tucous " + 
    "and violates formatting standards by making the line to long");

and compile the two Strings into one. 并将两个字符串编译成一个。 I'm pretty sure this is true but I would like to have my ducks in a row if anyone brings it up. 我很确定这是真的,但如果有人提出来的话,我想把我的鸭子连成两排。

Yes, this will be handled by the constant expression part of the Java Language Specification. 是的,这将由Java语言规范的常量表达式部分处理。 In particular see part 15.18.1. 特别参见第15.18.1部分 String Concatenation Operator + 字符串连接运算符+

Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. 由常量表达式计算的字符串(第15.28节)在编译时计算,然后将其视为文字。

Show that quote from the JLS to anyone who 'challenges' you. JLS的引用显示给任何“挑战”你的人。

To check if what JLS says about constant expressions is true I complied this code, Test.java 要检查JLS对常量表达式的说法是否正确,我遵守了此代码Test.java

public static void main(String[] args) {
    log.warning("123" + "456");
}

then decompile Test.class with Jad and got this 然后用Jad反编译Test.class并得到它

public static void main(String args[])
{
    log.warning("123456");
}

that is, in Test.class there is only one literal "123456" 也就是说,在Test.class中只有一个文字“123456”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM