I have often wondered this, is there a performance cost of splitting a string over multiple lines to increase readability when initially assigning a value to a string. I know that strings are immutable and therefore a new string needs to be created every time. Also, the performance cost is actually irrelevant thanks to today's really fast hardware (unless you are in some diabolical loop). So for example:
String newString = "This is a really long long long long long" +
" long long long long long long long long long long long long " +
" long long long long long long long long long string for example.";
How does the JVM or .Net's compiler and other optimizations handle this. Will it create a single string? Or will it create 1 string then a new concatenating the value and then another one concatenating the values again?
This is for my own curiosity.
This is guaranteed by the C# spec to be identical to creating the string in a single literal, because it's a compile-time constant. From section 7.18 of the C# 3 spec:
Whenever an expression fulfills the requirements listed above, the expression is evaluated at compile-time. This is true even if the expression is a sub-expression of a larger expression that contains non-constant constructs.
(See the spec for the exact details of "the requirements listed above" :)
The Java Language Specification specifies it near the bottom of section 3.10.5:
Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With