Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing big strings (e.g. for SQL commands) how smart is the C# compiler?

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?

like image 792
Alex from Jitbit Avatar asked Mar 06 '10 10:03

Alex from Jitbit


People also ask

What does C do in SQL?

C is saying that if the word C is found in context later in the SQL it is a reference to the table named productos . It is an alias for the table named immediately before the first occurance of C in your SQL query. Looks like simple alias for table products.

Is C similar to SQL?

To undestand the difference between a language like C and SQL is that basically SQL is a specialized type of language that is concerned with database operations. C is less concerned with accessing the data than with how the whole application will work.


2 Answers

Yes the compiler is smart enough to optimize constant string concatenations. To prove this let's examine the following method:

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

Compiled in Release mode this produces the following IL:

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

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 :-)

like image 76
Darin Dimitrov Avatar answered Sep 27 '22 20:09

Darin Dimitrov


Yes, the compiler will compute arithemetical operations on constant numbers and strings at compile time. However, the better way to answer performance questions like this is to try it yourself. Get out the StopWatch class, write the code both ways, run it a billion times in a loop, and then you'll know.

like image 20
Eric Lippert Avatar answered Sep 27 '22 20:09

Eric Lippert