views:

1111

answers:

5

For instance, would 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?

+20  A: 

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" including the + operator applied to two constant expressions.)

See also this question.

Jon Skeet
Same with VB.NET I would assume, right?
Larsenal
Not sure - it's a language issue, not a framework one.
Jon Skeet
Mind if I change the question then to C#?
Larsenal
@DLarsen: Good call :)
Jon Skeet
A: 

I believe the answer to that is yes, but you'd have to look at what the compiler spits out ... just compile, and use reflector on it :-)

Joel Martinez
+4  A: 

Yes.

C# not only optimizes the concatenation of string literals, it also collapses equivalent string literals into constants and uses pointers to reference all references to the same constant.

FlySwat
Do you have a reference for this information?
Justin Dearing
Its called "String Interning", and is covered in depth in the book CLR via C#.
FlySwat
+2  A: 

From the horses mouth:

"Concatenation is the process of appending one string to the end of another string. When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs. However, string variables can be concatenated only at run time. In this case, you should understand the performance implications of the various approaches. "

http://msdn.microsoft.com/en-us/library/ms228504.aspx

Kev
+7  A: 

Just a side note on a related subject - the C# compiler will also 'optimize' multiple concatenations involving non-literals using the '+' operator to a single call to a multi-parameter overload of the String.Concat() method.

So

string result = x + y + z;

compiles to something equivalent to

string result = String.Concat( x, y, z);

rather than the more naive possibility:

string result = String.Concat( String.Concat( x, y), z);

Nothing earth-shattering, but just wanted to add this bit to the discussion about string literal concatenation optimization. I don't know whether this behavior is mandated by the language standard or not.

Michael Burr