的if-else-Return或只是如果 - 返回? [英] If-Else-Return or just if-Return?
问题描述
假设我有一个收益
的如果
语句。从效率的角度来看,我应该使用
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
有人可以解释我的区别?是否有编译语言VS跨preTED之一的任何差别(例如C)(例如Python)的?
Can someone explain me the difference? Is there any difference in a compiled language (e.g. C) vs an interpreted one (e.g. Python)?
推荐答案
由于收益
语句终止当前函数的执行,这两种形式是等价的(虽然第二个可以说是比第一个更可读)。
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).
这两种形式的效率相媲美,底层机器code的,如果如果
条件为假反正进行跳转。
The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if
condition is false anyway.
请注意Python支持一种语法,可以让你在你的情况下,仅使用一个收益
语句:
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-else-Return或只是如果 - 返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!