返回内部if块或写if / else块之间是否存在性能差异?
我正在通过我的项目来重构一些代码,并意识到我写了这样的东西:
I was going through my project to refactor some code and realized I had written something like this:
if(errorCode > 0)
{
DisplayError(errorCode);
return;
}
// Continue to do stuff otherwise.
您可能已经猜到,该函数的返回类型为void。当我开始研究这个问题时,我思考是否将它放入if / else块之间是否有任何真正的区别:
As you may have guessed, the function has a return type of void. As I started to look this over, I pondered whether there was any real difference between putting this inside an if/else block instead:
if(errorCode > 0)
{
DisplayError(errorCode);
}
else
{
// Do other stuff
}
else块将一直持续到函数结束,因此控制流程基本相同。这里是否存在性能差异,或者应该使用的约定,或者这两者是否完全相同?
The else block will continue until the end of the function, so the flow of control is essentially the same. Is there a performance difference here, or a convention that should be used, or are these two really exactly the same?
两种情况下生成的代码完全相同。
The generated code in both cases is completely identical.
(在第一个示例中,您缺少代码周围的括号,但我只是假设这是一个错误而你实际上是询问使用返回
和否则
之间的差异。)
(You are missing brackets around the code in the first example, but I will just assume that it's a typo and you are actually asking about the difference betwen using return
and else
.)
如果你看一下这两种方法生成的代码:
If you look at the generated code for these two methods:
public static void Test1(int errorCode) {
if (errorCode > 0) {
Console.WriteLine(errorCode);
return;
}
Console.WriteLine("ok");
}
public static void Test2(int errorCode) {
if (errorCode > 0) {
Console.WriteLine(errorCode);
} else {
Console.WriteLine("ok");
}
}
它将如下所示:
if (errorCode > 0) {
011A00DA in al,dx
011A00DB push eax
011A00DC mov dword ptr [ebp-4],ecx
011A00DF cmp dword ptr ds:[10F3178h],0
011A00E6 je 011A00ED
011A00E8 call 7470C310
011A00ED cmp dword ptr [ebp-4],0
011A00F1 jle 011A0100
Console.WriteLine(errorCode);
011A00F3 mov ecx,dword ptr [ebp-4]
011A00F6 call 73C5A920
return;
011A00FB nop
011A00FC mov esp,ebp
011A00FE pop ebp
011A00FF ret
}
Console.WriteLine("ok");
011A0100 mov ecx,dword ptr ds:[3E92190h]
011A0106 call 7359023C
}
011A010B nop
011A010C mov esp,ebp
011A010E pop ebp
011A010F ret
和:
if (errorCode > 0) {
011A0122 in al,dx
011A0123 push eax
011A0124 mov dword ptr [ebp-4],ecx
011A0127 cmp dword ptr ds:[10F3178h],0
011A012E je 011A0135
011A0130 call 7470C310
011A0135 cmp dword ptr [ebp-4],0
011A0139 jle 011A0148
Console.WriteLine(errorCode);
011A013B mov ecx,dword ptr [ebp-4]
011A013E call 73C5A920
011A0143 nop
011A0144 mov esp,ebp
011A0146 pop ebp
011A0147 ret
} else {
Console.WriteLine("ok");
011A0148 mov ecx,dword ptr ds:[3E92190h]
011A014E call 7359023C
}
}
011A0153 nop
011A0154 mov esp,ebp
011A0156 pop ebp
011A0157 ret
生成的代码完全相同,一直到最后指示。
The generated code is completely identical, down to the last instruction.