Noc*_*tis 3 c# performance compiler-optimization
我遇到了一些反复检查相同条件的代码.好像C#6会让我们从这个丑陋的冗余代码中解脱出来,但与此同时,引入bool变量是否有任何好处,或者编译器足够聪明,可以为我们排序,而不是反复比较同样的事情?(即使我们正在进行检查,我会假设将结果藏在一个布尔会(稍微)更快?)
// here we're doing the same check over and over again
string str1 = (CustomerData == null) ? string.Empty : CustomerData.str1;
string str2 = (CustomerData == null) ? string.Empty : CustomerData.str2;
string str3 = (CustomerData == null) ? string.Empty : CustomerData.str3;
// ... rinse and repeat
// here we're still doing a check, but against a boolean variable
bool is_valid = CustomerData == null;
string str1 = is_valid ? string.Empty : CustomerData.str1;
string str2 = is_valid ? string.Empty : CustomerData.str2;
string str3 = is_valid ? string.Empty : CustomerData.str3;
// ... rinse and repeat
Run Code Online (Sandbox Code Playgroud)
在这种情况下,这可能并不重要,但如果比较2个对象然后需要深入检查其中的所有字段会发生什么?
注意:因为这是在方法内部,所以我不能依赖strings(null)的默认值,因此解决方法是创建所有字符串,将它们初始化为string.Empty,然后执行以下操作:
if (CustomerData != null) {
// set all of the above strings again, changing from empty to actual values
}
Run Code Online (Sandbox Code Playgroud)
为了扩展codenheim的答案,看起来,在Release版本中,JITter足够聪明,可以优化它们.
Debug构建执行所有比较并跳转很多.Release版本(无论如何在x64上)产生:
; string str1 = (CustomerData == null) ? string.Empty : CustomerData.str1;
call 000000005F64D620
mov rdx,0E7A80733A0h
mov rdx,qword ptr [rdx]
lea rdi,[rbp+10h]
mov rcx,rdi
call 000000005F64D620
mov rdx,0E7A80733A8h
mov rdx,qword ptr [rdx]
lea rbx,[rbp+18h]
mov rcx,rbx
call 000000005F64D620
mov rsi,qword ptr [rsi]
; string str2 = (CustomerData == null) ? string.Empty : CustomerData.str2;
mov rdi,qword ptr [rdi]
; string str3 = (CustomerData == null) ? string.Empty : CustomerData.str3;
mov rbx,qword ptr [rbx]
; string str6 = is_valid ? string.Empty : CustomerData.str3;
mov rbp,qword ptr [rbp+18h]
Run Code Online (Sandbox Code Playgroud)
它似乎只是忽略了你的代码,然后将数据移动到它应该知道的位置......给定之前评估的相同表达式的结果在那个时间点是已知的.