This may sound stupid but…
When I create big SQL commands I want to keep my code readable and I do this:
cmd.CommandText = "SELECT top 10 UserID, UserName " +
"FROM Users " +
"INNER JOIN SomeOtherTable ON xxxxx " +
"WHERE UserID IN (blablabla)";
See the concatenations? Now, to save performance I now do this:
cmd.CommandText = @"SELECT top 10 UserID, UserName
FROM Users
INNER JOIN SomeOtherTable ON xxxxx
WHERE UserID IN (blablabla)";
It keeps the code readable but saves concatenations. Now does it really save any performance or the compiler is smart enough to “pre-concatenate” the first string?
Yes the compiler is smart enough to optimize constant string concatenations. To prove this let’s examine the following method:
Compiled in Release mode this produces the following IL:
Notice the optimization. So in terms of performance both methods are identical. The only difference is that in the second case you will get new lines (\r\n) in the string, so they won’t produce the exactly same string but SQL Server is also smart enough 🙂