Normally I wouldn't ask this here, but I don't seem to have found any articles on what happens in this circumstance. Take the following example:
string s = "Potato";
string t = "Carrot, " + s + ", Bean";
In the second line, will the compiler optimize this to making a one string with Carrot added to the beginning and bean to the end, or will it create strings for Carrot and Bean, and then concatenate each to create the string?
I suppose different compilers may operate differently, but generally speaking what would happen here?
In the second line, will the compiler optimize this to making a one string with Carrot added to the beginning and bean to the end, or will it create strings for Carrot and Bean, and then concatenate each to create the string?
The latter, because s
isn't a compile-time constant expression. If you change the declaration of s
to:
const string s = "Potato";
... then it'll perform the concatenation at compile-time. You can validate this by compiling code that has both versions, and then using ildasm
to look at the result - in your case, you'll see a call to string.Concat(string, string, string)
whereas with const string s
you'll see the already-concatenated string in the IL.
See more on this question at Stackoverflow