Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is more efficient to use if-return-return or if-else-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

or

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

Should I prefer one or another when using a compiled language (C) or a scripted one (Python)?

like image 712
Jorge Leitao Avatar asked Oct 16 '22 05:10

Jorge Leitao


1 Answers

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
like image 261
Frédéric Hamidi Avatar answered Oct 18 '22 18:10

Frédéric Hamidi