It is more efficient to use if-return-return or if-else-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).
The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if
condition is false anyway.
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
From Chromium's style guide:
Don't use else after return:
# Badif (foo) return 1else return 2# Goodif (foo) return 1return 2return 1 if foo else 2
I personally avoid else
blocks when possible. See the Anti-if Campaign
Also, they don't charge 'extra' for the line, you know :p
"Simple is better than complex" & "Readability is king"
delta = 1 if (A > B) else -1return A + delta