Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# optimize the concatenation of string literals?

For instance, does the compiler know to translate

string s = "test " + "this " + "function"; 

to

string s = "test this function"; 

and thus avoid the performance hit with the string concatenation?

like image 539
Larsenal Avatar asked Nov 13 '08 23:11

Larsenal


People also ask

What does |= mean in C?

The ' |= ' symbol is the bitwise OR assignment operator.

Does C have do-while?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.


1 Answers

Yes. This is guaranteed by the C# specification. It's in section 7.18 (of the C# 3.0 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.

(The "requirements listed above" include the + operator applied to two constant expressions.)

See also this question.

like image 138
Jon Skeet Avatar answered Oct 14 '22 13:10

Jon Skeet