假设我有一个带有return的if语句。从效率的角度来看,我应该使用
if(A > B):
return A+1
return A-1
or
if(A > B):
return A+1
else:
return A-1
在使用编译语言(C)或脚本语言(Python)时,我应该选择其中一种还是另一种?
假设我有一个带有return的if语句。从效率的角度来看,我应该使用
if(A > B):
return A+1
return A-1
or
if(A > B):
return A+1
else:
return A-1
在使用编译语言(C)或脚本语言(Python)时,我应该选择其中一种还是另一种?
当前回答
任何明智的编译器,你应该观察到没有区别;它们应该被编译为相同的机器代码,因为它们是等效的。
其他回答
由于return语句终止了当前函数的执行,因此这两种形式是等效的(尽管可以说第二种形式比第一种形式更易于阅读)。
这两种形式的效率是相当的,如果if条件为假,底层机器码必须执行跳转。
注意,Python支持一种语法,允许你在你的情况下只使用一个return语句:
return A+1 if A > B else A-1
版本A更简单,这就是我使用它的原因。
如果你在Java中打开了所有的编译器警告,你会在第二个版本中得到一个警告,因为这是不必要的,而且会增加代码的复杂性。
我知道这个问题被标记为python,但它提到了动态语言,所以我想我应该提到,在ruby中,if语句实际上有一个返回类型,所以你可以这样做
def foo
rv = if (A > B)
A+1
else
A-1
end
return rv
end
或者因为它也有隐式回报
def foo
if (A>B)
A+1
else
A-1
end
end
这很好地解决了没有多次返回的风格问题。
任何明智的编译器,你应该观察到没有区别;它们应该被编译为相同的机器代码,因为它们是等效的。
这是一个风格(或偏好)的问题,因为解释器并不关心。就我个人而言,如果函数返回的值是缩进级别而不是函数基级别,那么我尽量不要在函数的最终语句中使用。例1中的else模糊了函数结束的位置,即使只是稍微模糊了一点。
根据偏好,我使用:
return A+1 if (A > B) else A-1
因为它既遵循了将单个return语句作为函数中的最后一条语句的良好约定(如前所述),又遵循了避免命令式中间结果的良好函数式编程范式。
For more complex functions I prefer to break the function into multiple sub-functions to avoid premature returns if possible. Otherwise I revert to using an imperative style variable called rval. I try not to use multiple return statements unless the function is trivial or the return statement before the end is as a result of an error. Returning prematurely highlights the fact that you cannot go on. For complex functions that are designed to branch off into multiple subfunctions I try to code them as case statements (driven by a dict for instance).
一些海报提到了操作速度。运行时的速度对我来说是次要的,因为如果你需要执行速度,Python不是最好的语言。我使用Python是因为它的编码效率(即编写无错误的代码)对我来说很重要。