简体   繁体   English

使用“+”运算符进行字符串连接后会创建多少个对象?

[英]How many objects are created after String concatenation using '+' operator?

I want to ask that how many objects are created after execution of the following statement in java.. 我想问一下在java中执行以下语句后创建了多少个对象。

String str = "a"+"b"+"c"+"d"

In my opinion, only one object should get created and that of StringBuilder. 在我看来,只应创建一个对象和StringBuilder的对象。 Please correct me and explain the logic behind it..thanks in advance. 请纠正我并解释它背后的逻辑......提前谢谢。

The simple answer is zero objects. 简单的答案是零对象。 That is a compile time constant expression, and the bytecode compiler evaluates it to "abcd" ... before creating the ".class" file. 这是一个编译时常量表达式,字节码编译器在创建“.class”文件之前将其评估为"abcd" ....

Actually, with modern JVMs, the instantiation of String objects associated with literals and compile time constant expressions is lazy, so a single String object may be created the first time that statement is executed. 实际上,对于现代JVM,与文字和编译时常量表达式相关联的String对象的实例化是惰性的,因此可以在第一次执行该语句时创建单个String对象。 But only the first time. 但只是一次。

So a more correct answer is either zero or one String objects, depending on: 所以更正确的答案是零或一个String对象,具体取决于:

  • the JVM implementation of string literal interning (lazy or eager), and 字符串文字实习(懒惰或渴望)的JVM实现,以及
  • whether this is the first execution of any statement that uses the "abcd" literal or compile time constant. 这是否是使用"abcd"文字或编译时常量的任何语句的第一次执行。

Then there is the possibility that the statement might be optimized away by the JIT compiler if str is never accessed. 如果从不访问str ,那么JIT编译器可能会优化该语句。

And it gets even more complicated if you consider the possibility of class unloading. 如果考虑类卸载的可能性,它会变得更加复杂。

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

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