Building large strings (e.g. for SQL commands), how smart is the C # compiler?

This may sound silly, but ...

When I create large 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 concatenation? Now, to maintain performance, I now do this:

 cmd.CommandText = @"SELECT top 10 UserID, UserName FROM Users INNER JOIN SomeOtherTable ON xxxxx WHERE UserID IN (blablabla)"; 

It retains readable code, but retains concatenation. Now does it really save any performance, or is the compiler smart enough to “pre-concatenate” the first line?

+6
c # string-concatenation
source share
2 answers

Yes, the compiler is smart enough to optimize constant string concatenations. To prove this, consider the following method:

 public static string Concat() { return "a" + "b"; } 

Compiled in Release mode, this calls the following IL:

 .method public hidebysig static string Concat() cil managed { .maxstack 8 L_0000: ldstr "ab" L_0005: ret } 

Pay attention to optimization. Thus, 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 line, so they won’t create exactly the same line, but SQL Server is also smart enough :-)

+10
source share

Yes, the compiler will calculate arithmetic operations with constant numbers and strings at compile time. However, the best way to answer these performance questions is to try it yourself. Exit the StopWatch class, write the code in both directions, run it a billion times in a loop, and then you will find out.

+6
source share

All Articles