0% found this document useful (0 votes)
83 views

It Is More Efficient To Use If-Return-Return or If-Else-Return?

Uploaded by

Manuel Asfd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

It Is More Efficient To Use If-Return-Return or If-Else-Return?

Uploaded by

Manuel Asfd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Products Customers Use cases Search… Log in Sign up

Home
It is more efficient to use if-return-return or if-else-return? Ask Question

PUBLIC Asked 8 years, 4 months ago Active 1 year, 3 months ago Viewed 204k times

Stack Overflow
Suppose I have an if statement with a return . From the efficiency
Tags The Overflow Blog
perspective, should I use
Users 140 Podcast 247: Paul explains it all
if(A > B):
Jobs
return A+1
return A-1 The Overflow #27: A simulation
TEAMS What’s this?
37 or Featured on Meta
Free 30 Day Trial

if(A > B): We're switching to CommonMark


return A+1
else:
New post lock available on meta sites:
return A-1
Policy Lock

Should I prefer one or another when using a compiled language (C) or a Feature test: Thank you reaction
scripted one (Python)?

python c performance compiler-construction What can we do to encourage


downvoting?

share improve this question follow edited Nov 14 '16 at 7:16

asked Feb 8 '12 at 10:20


Jorge Leitao
12.8k 14 69 99

11 In a compiled language you don't need to worry about efficiency much. The
By using our site, you acknowledge
compiler sortsthat
thatyou
out.have
You read
shouldand understand
write our
your code soCookie Policy,
you can Privacy
read it. (You Policy, and our Terms of Service.
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. – ams Feb 8 '12 at 11:58

5 Relying 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! – Andrew Jul 4 '13 at 21:05

1 If 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. – will
Oct 30 '14 at 16:02

7 How 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. – Jorge Leitao Nov 13 '16 at
6:47

1 While 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. – Emile Bergeron Nov 14 '16 at 2:12

show 4 more comments Jobs near you


AppSec Engineer (DAST)
8 Answers Active Oldest Votes
Hays Atlanta, GA

AppSec Engineer (Static and


Since the return statement terminates the execution of the current Dynamic Testing)
function, the two forms are equivalent (although the second one is Hays Atlanta, GA
191 arguably more readable than the first). dynamic

The efficiency of both forms is comparable, the underlying machine Be one of the first applicants
code has to perform a jump if the if condition is false anyway.
Principal Solution Architect
Note that Python supports a syntax that allows you to use only one Backbase Atlanta, GA
return statement in your case:
java continuous-integration

1 return A+1 if A > B else A-1 Senior Android Engineer


Stable Kernel Atlanta, GA
share improve this answer follow answered Feb 8 '12 at 10:25 kotlin android
Frédéric Hamidi
229k 36 439 449 Senior Software Engineer
T-Mobile USA Atlanta, GA
$111K - $135K
32 C supports that too. return (A>B)?A+1:A-1; However there is
python java
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 Senior Software Architect /
more vulnerable to implicit type promotions. – Lundin Feb 8 '12 at 10:51 Engineer who enjoys coding web
services in c#
47 @Lundin obfuscated? unreadable? Only for those who don't know the ternary MapLarge Atlanta, GA
operator. – glglgl Feb 8 '12 at 11:23
$100K - $150K REMOTE
6 @Lundin Following this argumentation, < is bad practice because -1 < single-page-application c#
1u produces an unexpected result. – glglgl Feb 8 '12 at 15:42

@glglgl: No, because people expect the ?: operator to behave as if-else, Security Engineer
3
which isn't true. If somebody would write code like -1 < 1u , which I doubt, Jvion Duluth, GA
they would easily spot the bug. Quite a lot of people would write some version security hipaa
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
Senior Data Scientist, Online
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. – The Home Depot Atlanta, GA
Lundin Feb 9 '12 at 12:11 python algorithm

6 @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 View more jobs on Stack Overflow
using the ternary in Python leads to unexpected results? – lvc Feb 10 '12 at
2:23
Linked
show 4 more comments

9 C/C++ conditional return statements


From Chromium's style guide:
2 else after continue, break or return
Don't use else after return:
32 1 Simple return function, what is more
Pythonic?
# Bad
if (foo) 0 Should I write else in case when return
return 1 inside if
else
return 2 95 Why should a function have only one exit-
point?
# Good
if (foo) 11 Pylint: Disable Unnecessary “else” after
return 1 “return” (no-else-return) warning
return 2
8 Best practice for compute the function
return value
return 1 if foo else 2
9 Is it preferable to use an “else” in Python
share improve this answer follow when it's not necessary?
edited Jun 18 '17 at 20:44
5 else vs return to use in a function to
prematurely stop processing

answered Jan 31 '15 at 10:20 0 Ruby's if / else in methods


skeller88
2,210 1 21 25 See more linked questions

1 Thanks. +1. May I ask why don't use else after return? – Tim Jun 18 '17 at Related
20:38
1718 Replacements for switch statement in
1 if-else is functionally equivalent, but it's verbose. The else is unnecessary. –
Python?
skeller88 Jun 18 '17 at 20:43
1556 How to efficiently count the number of
17 I was surprised because the first seems more clear and thus better. – Tim Jun
keys/properties of an object in JavaScript?
18 '17 at 20:44
543 Why does C++ compilation take so long?
4 You could make a reasonable case for either. The most important thing in this
decision IMO is to be consistent within the code base. – skeller88 Jun 18 '17
at 20:46 2987 Improve INSERT-per-second performance
of SQLite
2 you'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 676 Speed comparison with Project Euler: C vs
anyway; either using a switch construct or for Python, enumerating a Python vs Erlang vs Haskell
dict/using a callable/etc.). Therefore almost all if-else-return are cases
440 Is it a good practice to use try-except-else
of guard clauses and those are always testable (mock the tested expression)
in Python?
without the else . – cowbert Mar 28 '18 at 3:22
1251 \d is less efficient than [0-9]
show 4 more comments
929 Swift Beta performance: sorting arrays

Regarding coding style: 1430 Replacing a 32-bit loop counter with 64-bit
introduces crazy performance deviations
Most coding standards no matter language ban multiple return with _mm_popcnt_u64 on Intel CPUs
5 statements from a single function as bad practice.
Hot Network Questions
(Although personally I would say there are several cases where multiple
return statements do make sense: text/data protocol parsers, functions What is a tee equivalent for network packets?
with extensive error handling etc)
Why do Gondorians frequently refer to Gandalf as
The consensus from all those industry coding standards is that the Mithrandir?
expression should be written as: How do I insert sub-bullets in a table environment?

Why Not Prune Your Neural Network?


i t lt
int result;
Can you naturally grow houses?
if(A > B)
{ Does there exist an operation that could turn the
result = A+1; set of all negative real numbers into an abelian
} group?
else
For a level 10 Swords bard with Crossbow Expert,
{ Sharpshooter, when is it better for DPR to use
result = A-1; Greater Invisibility vs. Swift Quiver?
}
return result; Operation on the first element of list only

People running into the shadows to hide from killer


sunlight, climbing scene
Regarding efficiency: Safe place online for children to play against
others
The above example and the two examples in the question are all
What was this beacon-like light in the distance that
completely equivalent in terms of efficiency. The machine code in all disappeared?
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 Are planes allowed to fly in circles, and is there a
minimum legal altitude for overflying populated
the stack. areas?

EDIT : How to express "Anonymous" when functioning as


a proper noun?
Sources: Is it grammatically correct to use "them" with hair?

MISRA-C:2004 rule 14.7, which in turn cites...: How can I understand this puzzling dialogue with
"ну я имею в виду вообще"?
IEC 61508-3. Part 3, table B.9.
Why are Disc Brakes better in the Rain?
IEC 61508-7. C.2.9.
Why is my recursive CTE so much slower on
Azure SQL?
share improve this answer follow edited Jun 11 '13 at 12:45
Latin for "the new darkness"

What's the purpose of tying a thread or dental


floss on either side of a kitten's umbilical cord?
answered Feb 8 '12 at 10:47
How to use \NewDocumentCommand
Lundin
137k 21 185 301 How to find the smallest position of an element of
an ascending list {1,4,10,12,20} such that the
element is not less than 11?
37 Are you sure the single-return religion has infected most coding standards?
Looking For Title of Circa 1990s English-Language
That would be frightening. – Daniel Fischer Feb 8 '12 at 10:52
Sci-Fi Film
7 I would say the rule doesn't make sense most of the time. I tend to find code If a Devotion God had a tap ability, would it be able
more readable and easier to follow with returns at appropriate points. But to tap on the turn it came in if you didn't have
pp p p to tap on the turn it came in if you didn t have
that's just me. However, I thought of per company/project coding standards, enough devotion?
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. – Did playing sounds on the PC speaker keep the
Daniel Fischer Feb 8 '12 at 13:33 CPU busy?

3 @DanielFischer: In the C coding standard based on MISRA that I designed


Question feed
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. –
Lundin Feb 8 '12 at 15:37

6 See 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. – John Y Jun 11 '13 at 13:55

1 @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. – Lundin Apr 5 '19 at 6:45

show 2 more comments

With any sensible compiler, you should observe no difference; they


should be compiled to identical machine code as they're equivalent.
3 share improve this answer follow edited Feb 8 '12 at 10:29

answered Feb 8 '12 at 10:22


Oliver Charlesworth
244k 26 506 625
add a comment

This is a question of style (or preference) since the interpreter does not
care. Personally I would try not to make the final statement of a function
which returns a value at an indent level other than the function base.
2
The else in example 1 obscures, if only slightly, where the end of the
function is.

By preference I use:

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

As it obeys both the good convention of having a single return


statement as the last statement in the function (as already mentioned)
and the good functional programming paradigm of avoiding imperative
style intermediate results.

For more complex functions I prefer to break the function into multiple
sub-functions to avoid premature returns if possible. Otherwise I revert
to using an imperative style variable called rval. I try not to use multiple
return statements unless the function is trivial or the return statement
before the end is as a result of an error. Returning prematurely
highlights the fact that you cannot go on. For complex functions that are
designed to branch off into multiple subfunctions I try to code them as
case statements (driven by a dict for instance).

Some posters have mentioned speed of operation. Speed of Run-time


is secondary for me since if you need speed of execution Python is not
the best language to use. I use Python as its the efficiency of coding
(i.e. writing error free code) that matters to me.

share improve this answer follow edited Nov 26 '18 at 13:27

answered Feb 16 '17 at 16:25


Stephen Ellwood
316 2 10
1 If a user is going to down-vote my answer I would appreciate a comment as to
why they thought I was wrong. – Stephen Ellwood Feb 17 '17 at 9:04

I 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
– percebus Jun 5 '17 at 14:30

@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 – Stephen Ellwood Nov 26 '18 at 13:34

BTW I actually upvoted your answer. If you see my answer is rather similar –
percebus Nov 27 '18 at 23:15

add a comment

I personally avoid else blocks when possible. See the Anti-if


Campaign
2 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

share improve this answer follow edited Nov 27 '18 at 22:57

answered Nov 26 '18 at 23:21


percebus
551 1 6 16

2 Why 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 Nov 27 '18 at 22:54

3 I 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 Nov 29 '18 at
12:56

1 Did 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. – Stephen Ellwood Nov 29 '18 at 13:02

1 @StephenEllwood Using dict s to avoid diffs is a very bad idea


performance-wise. – Bachsau Oct 6 '19 at 4:21

@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. – Stephen Ellwood Oct 7 '19 at 22:10

add a comment

Version A is simpler and that's why I would use it.

And if you turn on all compiler warnings in Java you will get a warning
1 on the second Version because it is unnecesarry and turns up code
complexity.

share improve this answer follow answered Feb 8 '12 at 10:23


juergen d
178k 29 238 302

add a comment

I know the question is tagged python, but it mentions dynamic


languages so thought I should mention that in ruby the if statement
actually has a return type so you can do something like
1
def foo
rv = if (A > B)
A+1
else
A-1
end
return rv
end
Or because it also has implicit return simply

def foo
if (A>B)
A+1
else
A-1
end
end

which gets around the style issue of not having multiple returns quite
nicely.

share improve this answer follow answered Feb 1 '18 at 12:59


Jamie Cook
3,707 3 34 48

add a comment

Highly active question. Earn 10 reputation in order to answer this question. The
reputation requirement helps protect this question from spam and non-answer
activity.

Not the answer you're looking for? Browse other questions tagged python

c performance compiler-construction or ask your own question.

STACK OVERFLOW PRODUCTS COMPANY STACK EXCHANGE Blog Facebook Twitter LinkedIn Instagram
NETWORK
Questions Teams About
Technology
Jobs Talent Press
Life / Arts
Developer Jobs Directory Advertising Work Here
Culture / Recreation
Salary Calculator Enterprise Legal
Science
Help Privacy Policy
Other
Other
Mobile Contact Us site design / logo © 2020 Stack Exchange Inc; user
contributions licensed under cc by-sa.
Disable Responsiveness rev 2020.6.26.37146

You might also like