Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the performance cost of assigning a single string value using +'s

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.

like image 636
uriDium Avatar asked Mar 02 '09 09:03

uriDium


1 Answers

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.

like image 172
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet