Java invariance, using the “=” operator

The questions about string invariance in java have plenty, in which the author of the problem actually reassigns references

However, there is a significant case where there seems to be no reallocation of strings:

String s = "hello";
s += " world";

You think of it as an actual modification of the string Try it at home

I'm sure it's a syntax sugar and translated by the compiler into something with the same semantics:

String s = "hello";
s = s + " world";

Can anyone confirm this fact?

Solution

I can neither confirm nor deny it If the optimization compiler can prove to itself that no other thread can "see" the initial (pre - =) value of S, it is free to optimize the concatenation and compile the code into an equivalent

String s = "hello world";

As long as the compiler follows the memory model, the compiler is free to convert them from source code to byte code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>