问题描述
我已经看到两种不同的方法,使一个布尔返回方式:
I've now seen two different ways to make a boolean returning method:
bool Case1()
{
if (A)
return true;
else
return false;
}
bool Case2()
{
if (A)
return true;
return false;
}
哪一个是更快?是否有意义,以不写其他
只是为了节省一条线,使其更清晰,或者是有一个微不足道的性能提升?
Which one is faster? Does it make sense to not write else
just to save a line, make it clearer, or is there a negligible performance gain?
推荐答案
即使我们看看他们的 IL
code,它们有相同的 IL
code ,所以它们之间没有性能差异。 使用的其中一个更便于你阅读
No.
Even when we look at their IL
code, they have the same IL
code, so there is no performance difference between them. Use the one which is more readable for you.
.method private hidebysig instance bool Case1() cil managed
{
// Code size 9 (0x9)
.maxstack 1
.locals init ([0] bool CS$1$0000,
[1] bool CS$4$0001)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.1
IL_0003: ldc.i4.1
IL_0004: stloc.0
IL_0005: br.s IL_0007
IL_0007: ldloc.0
IL_0008: ret
} // end of method Program::Case1
看看这些作品code为他们的表演;
Look at these pieces of code for their performances;
http://ideone.com/8Sc7Ho - >内存:33856 KB
http://ideone.com/MrnaAl - >内存:33808 KB
http://ideone.com/MrnaAl --> Memory: 33808 kB
所以,如果你甚至可以用它们10.000倍,没有什么可担心的。
So if you use them even 10.000 times, there is nothing to worry about.
这篇关于不要紧,性能明智的,如果有第一个`return`后`else`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!