简体   繁体   English

漂亮格式的.NET代码中的SQL,性能如何?

[英]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. 你知道sql有多复杂。

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: 在发布模式下,生成的IL是:

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

So .NET does optimize "pretty formatted strings". 所以.NET确实优化了“非常格式化的字符串”。

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... 拥有内联SQL字符串是否是一个好主意完全是另一回事......

Ah - one of the eternal verities of C#. 啊 - 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. 在您的情况下,答案取决于您使用的.NET版本.NET1到目前为止只能在单个语句中优化+字符串。 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. 从.NET 2开始,体系结构略有改变,编译器将多个+语句无缝连接在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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