It Is More Efficient To Use If-Return-Return or If-Else-Return?
It Is More Efficient To Use If-Return-Return or If-Else-Return?
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
Should I prefer one or another when using a compiled language (C) or a Feature test: Thank you reaction
scripted one (Python)?
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
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
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
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?
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"
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?
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
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:
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).
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
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
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
@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
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.
add a comment
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.
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
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