It is more efficient to use if-return-return or if-else-return?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping
--
Chapters
00:00 It Is More Efficient To Use If-Return-Return Or If-Else-Return?
00:29 Answer 1 Score 5
00:41 Accepted Answer Score 283
01:11 Answer 3 Score 8
02:22 Answer 4 Score 58
02:32 Thank you
--
Full question
https://stackoverflow.com/questions/9191...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #c #performance #compilerconstruction
#avk47
ACCEPTED ANSWER
Score 283
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
ANSWER 2
Score 58
From Chromium's style guide:
Don't use else after return:
# Bad
if (foo)
return 1
else
return 2
# Good
if (foo)
return 1
return 2
return 1 if foo else 2
ANSWER 3
Score 8
Regarding coding style:
Most coding standards no matter language ban multiple return statements from a single function as bad practice.
(Although personally I would say there are several cases where multiple return statements do make sense: text/data protocol parsers, functions with extensive error handling etc)
The consensus from all those industry coding standards is that the expression should be written as:
int result;
if(A > B)
{
result = A+1;
}
else
{
result = A-1;
}
return result;
Regarding efficiency:
The above example and the two examples in the question are all completely equivalent in terms of efficiency. The machine code in all these cases have to compare A > B, then branch to either the A+1 or the A-1 calculation, then store the result of that in a CPU register or on the stack.
EDIT :
Sources:
- MISRA-C:2004 rule 14.7, which in turn cites...:
- IEC 61508-3. Part 3, table B.9.
- IEC 61508-7. C.2.9.
ANSWER 4
Score 5
With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.