How many String objects will be created when using a plus sign in the below code?
String result = "1" + "2" + "3" + "4";
If it was as below, I would have said three String objects: “1”, “2”, “12”.
String result = "1" + "2";
I also know that String objects are cached in the String Intern Pool/Table for performance improvement, but that’s not the question.
Surprisingly, it depends.
If you do this in a method:
then the compiler seems to emit the code using
String.Concatas @Joachim answered (+1 to him btw).If you define them as constants, e.g.:
or as literals, as in the original question:
then the compiler will optimize away those
+signs. It’s equivalent to:Furthermore, the compiler will remove extraneous constant expressions, and only emit them if they are used or exposed. For instance, this program:
Only generates one string- the constant
result(equal to “1234”).oneandtwodo not show up in the resulting IL.Keep in mind that there may be further optimizations at runtime. I’m just going by what IL is produced.
Finally, as regards interning, constants and literals are interned, but the value which is interned is the resulting constant value in the IL, not the literal. This means that you might get even fewer string objects than you expect, since multiple identically-defined constants or literals will actually be the same object! This is illustrated by the following:
In the case where Strings are concatenated in a loop (or otherwise dynamically), you end up with one extra string per concatenation. For instance, the following creates 12 string instances: 2 constants + 10 iterations, each resulting in a new String instance:
But (also surprisingly), multiple consecutive concatenations are combined by the compiler into a single multi-string concatenation. For example, this program also only produces 12 string instances! This is because “Even if you use several + operators in one statement, the string content is copied only once.“