假设我有一个带有return的if语句。从效率的角度来看,我应该使用

if(A > B):
    return A+1
return A-1

or

if(A > B):
    return A+1
else:
    return A-1

在使用编译语言(C)或脚本语言(Python)时,我应该选择其中一种还是另一种?


当前回答

我知道这个问题被标记为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

这很好地解决了没有多次返回的风格问题。

其他回答

版本A更简单,这就是我使用它的原因。

如果你在Java中打开了所有的编译器警告,你会在第二个版本中得到一个警告,因为这是不必要的,而且会增加代码的复杂性。

从性能的角度来看,这在Python中并不重要,我认为对所有现代语言都是如此。

归根结底是风格和可读性。第二个选项(if-else块)比第一个更具可读性,而且比一行三元操作可读性强得多。

来自Chromium的风格指南:

返回后不要使用else:

# Bad
if (foo)
  return 1
else
  return 2

# Good
if (foo)
  return 1
return 2

return 1 if foo else 2

如果可能的话,我个人会尽量避免其他阻塞。参见反if运动

而且,他们不收“额外”的费用,你知道:p

“简单胜于复杂”&“可读性为王”

delta = 1 if (A > B) else -1
return A + delta

这是一个风格(或偏好)的问题,因为解释器并不关心。就我个人而言,如果函数返回的值是缩进级别而不是函数基级别,那么我尽量不要在函数的最终语句中使用。例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是因为它的编码效率(即编写无错误的代码)对我来说很重要。