使用 if-return-return 还是 if-else-return 效率更高? [英] It is more efficient to use if-return-return or if-else-return?
问题描述
假设我有一个带有 return
的 if
语句.从效率的角度来看,我应该使用
Suppose I have an if
statement with a return
. From the efficiency perspective, should I use
if(A > B):
return A+1
return A-1
或
if(A > B):
return A+1
else:
return A-1
在使用编译语言 (C) 还是脚本语言 (Python) 时,我应该选择一种还是另一种?
Should I prefer one or another when using a compiled language (C) or a scripted one (Python)?
推荐答案
由于 return
语句终止了当前函数的执行,所以两种形式是等价的(虽然第二种形式可以说更具可读性比第一个).
Since the return
statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).
两种形式的效率相当,如果if
条件为假,底层机器代码必须执行跳转.
The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if
condition is false anyway.
请注意,Python 支持的语法允许您在您的情况下仅使用一个 return
语句:
Note that Python supports a syntax that allows you to use only one return
statement in your case:
return A+1 if A > B else A-1
这篇关于使用 if-return-return 还是 if-else-return 效率更高?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!