简体   繁体   中英

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.

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.

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".

You can use

string s = @"SELECT *
FROM person
WHERE id = :id";

String constants are folded at compile time so the two code fragments above are essentially identical.

Whether it's a good idea to have inline SQL string is another matter entirely...

Ah - one of the eternal verities of C#. Which is better, code that concatenates strings using + or code that doesn't? In your case, the answer depends on which version of .NET you're using .NET1 could only optimize the + string in a single statement so far. Too many + in a single string resulted in poorer performance as the compiler had to resort to creating new string instances to cope with additional string parts. From .NET 2, the architecture changed slightly, and multiple + statements are concatenated quite seamlessly by the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM