Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty format sql in .NET code, performance?

Will the compiler optimize pretty formatted strings, or will that code run slower than strings that are not divided in a readable way?

for example

string sql = 
   "select * " +
   "from person " +
   "where id = :id";

or

string sql = "select * from person where id = :id";

This is just a small example. You know how complicated the sql can get.

like image 657
kaze Avatar asked Nov 05 '09 12:11

kaze


2 Answers

Just use:-

string sql = 
   @"select * 
     from person
     where id = :id";

This is from the compilers point of view identical to the single line solution. Although I wouldn't be surprised to see the concatenation of literal strings optimised out by the compiler anyway. However the common gotcha with the concatenation approach is forgetting to include whitespace at the end of string.

like image 104
AnthonyWJones Avatar answered Oct 21 '22 03:10

AnthonyWJones


You can test this with a simple program:

Console.WriteLine("a" + "b");

Using reflector, you can easily disassemble the resulting binary. In Release mode, the IL this generates is:

L_0000: ldstr "ab"
L_0005: call void [mscorlib]System.Console::WriteLine(string)

So .NET does optimize "pretty formatted strings".

like image 40
Andomar Avatar answered Oct 21 '22 05:10

Andomar