It is more efficient to use if-return-return or if-else-return?
Solution 1
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
Solution 2
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
Solution 3
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 -1
return A + delta
Solution 4
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.
Solution 5
With any sensible compiler, you should observe no difference; they should be compiled to identical machine code as they're equivalent.
Related videos on Youtube
Jorge Leitao
All content I created on this website until Sep 5 2019, at 13:53 is licensed under 3.0 CC BY-SA, and not 4.0 CC BY-SA as SO states.
Updated on February 27, 2021Comments
-
Jorge Leitao over 3 years
Suppose I have an
if
statement with areturn
. From the efficiency perspective, should I useif(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)?
-
ams over 12 yearsIn a compiled language you don't need to worry about efficiency much. The compiler sorts that out. You should write your code so you can read it. (You still have to worry about the efficiency of your algorithms, and sloppy use of types etc. will affect efficiency - you just don't have worry about your style too much.) I don't know about Python though.
-
Andrew almost 11 yearsRelying on your compiler to sort out your code is a dangerous step - and requires an infallible compiler. Better if you know whay tou want your code to do!
-
will over 9 yearsIf what you are doing is defined by the spec, then i do not believe there is any reason to doubt the compiler. It will have been written be people far smarter than you, and it's far more likely that you made a mistake than them.
-
Jorge Leitao over 7 yearsHow can this be closed for opinion based? It may be an opinion after you know that there is no performance difference between the two. I did not, and I am pretty sure that a lot of people also did not.
-
Emile Bergeron over 7 yearsWhile the question is quite popular, it can't be answered accurately without a specific language in mind, or otherwise, answering for every languages would be too long for this format.
-
Jorge Leitao over 7 years@EmileBergeron: the relevant tags for languages were removed in an edit for some reason. I added them back and updated the question respectively. Please also see meta.stackoverflow.com/q/337800/931303
-
Braiam over 7 years@EmileBergeron actually, language doesn't matter. The compiler/interpreter, on the other hand, does.
-
Emile Bergeron over 7 years@Braiam I agree, but before we talk about a compiler/interpreter, we need to decide on which language we want to discuss.
-
percebus over 5 yearsAs replied by @ams , Usually you don't need to focus much on optimizations. Furthermore, preemptive optimization is considered a bad practice. “It is far, far easier to make a correct program fast than to make a fast program correct.” – Herb Sutter hygger.io/blog/programming-quotes-42
-
-
Lundin over 12 yearsC supports that too.
return (A>B)?A+1:A-1;
However there is absolutely no gain in performance from writing the code like this. All we have achieved is to make the code obfuscated, unreadable and in some cases more vulnerable to implicit type promotions. -
Daniel Fischer over 12 yearsAre you sure the single-return religion has infected most coding standards? That would be frightening.
-
glglgl over 12 years@Lundin obfuscated? unreadable? Only for those who don't know the ternary operator.
-
Jorge Leitao over 12 yearsOk, I understand that. My point is that different things happens when the language is compiled or interpreted. As @ams pointed out on a comment, compiler does have an influence on the performance. Can you add to this answer some information on that so I can accept it?
-
Frédéric Hamidi over 12 years@J.C.Leitão, well, Python code is usually compiled to intermediate language code (depending on the implementation), so ams's comment does apply here: you shouldn't worry too much about style.
-
Daniel Fischer over 12 yearsI would say the rule doesn't make sense most of the time. I tend to find code more readable and easier to follow with returns at appropriate points. But that's just me. However, I thought of per company/project coding standards, not things like MISRA where otherwise idiotic prescriptions may occasionally have some merit. I hope most didn't buy into the single exit-point idea.
-
Lundin over 12 years@DanielFischer: In the C coding standard based on MISRA that I designed for my company, I have the rule "A function shall only have a single point of exit, at the end of the function, unless a single point of exit makes the code less readable". So it is MISRA-C but with an exception to the rule. If you write an advanced parser function which can return lets say 10 differt errors, the level of nested braces make the code completely unreadable - in such a case it would be more sensible to return immediately as an error is encountered.
-
glglgl over 12 years@Lundin Following this argumentation,
<
is bad practice because-1 < 1u
produces an unexpected result. -
Daniel Fischer over 12 yearsThat's okay. I think we'd (hypothetically) have some arguments over when the readability clause applies, but a reasonable compromise should be attainable.
-
Lundin over 12 years@glglgl: No, because people expect the ?: operator to behave as if-else, which isn't true. If somebody would write code like
-1 < 1u
, which I doubt, they would easily spot the bug. Quite a lot of people would write some version of the code I posted however. I have seen such bugs far too often in production code to trust the ?: operator. Also as a rule of thumb, if the language gives you two different ways to do the same thing, only use one of them, don't randomly pick either of the two depending on your mood. -
lvc over 12 years@Lundin that is an argument for being careful with ?: in C, but you seem to be saying it applies to Python as well. Can you point to any examples where using the ternary in Python leads to unexpected results?
-
Lundin over 12 years@lvc No, I have no idea of how Python handles implicit type promotions in various operators.
-
John Y about 11 yearsSee this SO question for a discussion and further links to further discussions on the single-exit-point issue. Besides the single-exit-point rule being old-fashioned and overly "engineeringy", Python specifically promotes a "flat is better than nested" view, and putting
return
wherever it happens to be clear is the idiomatic way to do it in Python. -
Stephen Ellwood over 7 yearsIf a user is going to down-vote my answer I would appreciate a comment as to why they thought I was wrong.
-
percebus about 7 yearsI would probably just a line before to make it 1 line per statement for readability purposes.
var n = 1 if (A > B) else -1
return A+n
-
Tim almost 7 yearsThanks. +1. May I ask why don't use else after return?
-
skeller88 almost 7 yearsif-else is functionally equivalent, but it's verbose. The else is unnecessary.
-
Tim almost 7 yearsI was surprised because the first seems more clear and thus better.
-
skeller88 almost 7 yearsYou could make a reasonable case for either. The most important thing in this decision IMO is to be consistent within the code base.
-
cowbert over 6 years@Lundin python is duck-typed so there is no such thing as "implicit type promotion". Operators are implemented as special methods by the nearest (via MRO) abstract class that defines the type.
-
iJames about 6 yearsWhat about ensuring clean branch coverage in testing? The lack of the
else
still leaves it implicit making unit testing less clear, right? -
skeller88 about 6 yearsThat's an interesting point. I'm not sure how various test coverage checking software will handle one format vs. the other. Like I said, I have no strong preference since they have similar performance. The first case is more verbose but judging by the comments on this SO thread, more readable. The second case is recommended by Chromium, which means maybe more developers will recognize that format. More important than either option is being consistent in a code base.
-
cowbert about 6 yearsyou'll probably find in the majority of cases that
if-else-return
branches are almost never equal (if they are, then you should be refactoring anyway; either using aswitch
construct or for Python, enumerating a dict/using a callable/etc.). Therefore almost allif-else-return
are cases of guard clauses and those are always testable (mock the tested expression) without theelse
. -
Stephen Ellwood over 5 years@percebus in some cases I would agree if the variable name can enhance the meaning. For instance: 'code' move_x = 1 if my_x < opponent_x else -1 # move towards opponent
-
percebus over 5 yearsWhy the down vote? Is a 'pythonic' answer. You might not consider it a preferred answer. But is not an invalid one. I am also following the KISS Principle en.wikipedia.org/wiki/KISS_principle
-
percebus over 5 yearsI think that the fear of Cyclomatic Complexity is more a C/C++ phenomena than anything else en.wikipedia.org/wiki/Cyclomatic_complexity Single returns lead to nested if/else hell and are discouraged as anti-patterns. francescocirillo.com/pages/anti-if-campaign Lastly, in your example, you can reduce the confusion with if (A > B) { return A +1 } # implicit else return A -1 {code}
-
percebus over 5 yearsBTW I actually upvoted your answer. If you see my answer is rather similar
-
Stephen Ellwood over 5 yearsI upvoted your answer since for me it scores on readability and simple. I personally find it offensive is someone down-votes me without educating me on why my answer is actively negative.
-
Stephen Ellwood over 5 yearsDid not hear before about the Anti-if campaign but can understand why ifs can be dangerous. I always try to limit the amount of code enclosed by an if statement and try to rewrite elif trees to use dict. This is getting a bit off-topic though.
-
Lundin about 5 years@percebus I completely agree and cyclomatic complexity is a good argument against single return. And I've been poking the MISRA committee about this several times, for example see this. At least the rule got downgraded to advisory in MISRA-C:2012.
-
c z about 5 yearsIn Python, you could put a blank line in place of the
else
, then it will match the good solution, and be readable too. -
skeller88 about 5 years@cz Where's a link to that style?
-
Bachsau over 4 years@StephenEllwood Using
dict
s to avoid diffs is a very bad idea performance-wise. -
Stephen Ellwood over 4 years@Bachsau You are probably right. I've never had to worry about performance as all my scripts run in seconds. For me readability usually trumps performance. Since I'm not a full time programmer; they are just a means to an end.
-
cikatomo over 3 yearsI don't buy it. Reading one word 'else' is way more brain efficient than to mentally figure it out what's going on. Even if it's obvious. One word: 'else' will always be more obvious. Psychology 101