It is more efficient to use if-return-return or if-else-return?
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
Java: if-return-if-return vs if-return-elseif-return
The generated byte code is identical for those two cases, so it's purely a matter of style.
I produced two methods e1
and e2
and both produced this byte code (read using javap -v
):
public boolean e1(java.lang.Object);
Code:
Stack=2, Locals=2, Args_size=2
0: aload_0
1: aload_1
2: if_acmpne 7
5: iconst_1
6: ireturn
7: aload_1
8: ifnonnull 13
11: iconst_0
12: ireturn
13: aload_0
14: invokevirtual #25; //Method java/lang/Object.getClass:()Ljava/lang/Class;
17: aload_1
18: invokevirtual #25; //Method java/lang/Object.getClass:()Ljava/lang/Class;
21: if_acmpeq 26
24: iconst_0
25: ireturn
I left out the code I put after that to make it compile.
What would be more efficient in java? If-return-else or If-return?
No performance difference. The bytecode contains the same instructions, in the same order, operating on the same data.
L0
LINENUMBER 11 L0
ICONST_1
ISTORE 0
L1
LINENUMBER 12 L1
ILOAD 0
IFEQ L2
L3
LINENUMBER 13 L3
GETSTATIC p/A.something : Ljava/lang/Object;
ARETURN
L2
LINENUMBER 15 L2
FRAME APPEND [I]
INVOKESTATIC p/A.dosomething()V
L4
LINENUMBER 17 L4
ACONST_NULL
ARETURN
L5
LOCALVARIABLE condition Z L1 L5 0
MAXSTACK = 1
MAXLOCALS = 1
vs.
L0
LINENUMBER 7 L0
ICONST_1
ISTORE 0
L1
LINENUMBER 8 L1
ILOAD 0
IFEQ L2
L3
LINENUMBER 9 L3
GETSTATIC p/B.something : Ljava/lang/Object;
ARETURN
L2
LINENUMBER 11 L2
FRAME APPEND [I]
INVOKESTATIC p/B.dosomething()V
L4
LINENUMBER 12 L4
ACONST_NULL
ARETURN
L5
LOCALVARIABLE condition Z L1 L5 0
MAXSTACK = 1
MAXLOCALS = 1
public class A {
static Object something = new Object();
public static void main(String[] args) {
test();
}
private static Object test() {
boolean condition = true;
if (condition) {
return something;
} else {
dosomething();
}
return null;
}
private static void dosomething() {}
}
vs.
public class B {
static Object something = new Object();
public static void main(String[] args) {
test();
}
private static Object test() {
boolean condition = true;
if (condition) {
return something;
}
dosomething();
return null;
}
private static void dosomething() {}
}
C# better if/return or if/return/else?
I think the example you have given is just for demonstrations purposes. However, in general, it's just a matter of readability, there is no performance difference as compiler does the optimizations. Personnally I prefer the way you have done it by returning. If you have a longer logic it's more readable to understand certain invalid scenarios. And also cleaner than nested if/else blocks. Just my opinion.
In C, which is faster: if with returns, or else if with returns?
It makes no difference, and this is a needless attempt at micro-optimization.
What's faster ? if()return;else return; OR if()return; return;
Just:
return !false;
So in real-life example
return !$this->isSth();
// Not
if ($this->isSth) {
return false;
} else {
return true;
}
Performance isn't important here - every solution is extremely fast, there is no need for optimization. Remember the words of Donald Knuth:
Premature optimization is the root of all evil
If statement vs if-else statement, which is faster?
TL;DR: In unoptimized code, if
without else
seems irrelevantly more efficient but with even the most basic level of optimization enabled the code is basically rewritten to value = condition + 5
.
I gave it a try and generated the assembly for the following code:
int ifonly(bool condition, int value)
{
value = 5;
if (condition) {
value = 6;
}
return value;
}
int ifelse(bool condition, int value)
{
if (condition) {
value = 6;
} else {
value = 5;
}
return value;
}
On gcc 6.3 with optimizations disabled (-O0
), the relevant difference is:
mov DWORD PTR [rbp-8], 5
cmp BYTE PTR [rbp-4], 0
je .L2
mov DWORD PTR [rbp-8], 6
.L2:
mov eax, DWORD PTR [rbp-8]
for ifonly
, while ifelse
has
cmp BYTE PTR [rbp-4], 0
je .L5
mov DWORD PTR [rbp-8], 6
jmp .L6
.L5:
mov DWORD PTR [rbp-8], 5
.L6:
mov eax, DWORD PTR [rbp-8]
The latter looks slightly less efficient because it has an extra jump but both have at least two and at most three assignments so unless you really need to squeeze every last drop of performance (hint: unless you are working on a space shuttle you don't, and even then you probably don't) the difference won't be noticeable.
However, even with the lowest optimization level (-O1
) both functions reduce to the same:
test dil, dil
setne al
movzx eax, al
add eax, 5
which is basically the equivalent of
return 5 + condition;
assuming condition
is zero or one.
Higher optimization levels don't really change the output, except they manage to avoid the movzx
by efficiently zeroing out the EAX
register at the start.
Disclaimer: You probably shouldn't write 5 + condition
yourself (even though the standard guarantees that converting true
to an integer type gives 1
) because your intent might not be immediately obvious to people reading your code (which may include your future self). The point of this code is to show that what the compiler produces in both cases is (practically) identical. Ciprian Tomoiaga states it quite well in the comments:
a human's job is to write code for humans and let the compiler write code for the machine.
Why we use if, else if instead of multiple if block if the body is a return statement
if-elseif-else
statements stop doing comparisons as soon as it finds one that's true. if-if-if
does every comparison. The first is more efficient.
Edit: It's been pointed out in comments that you do a return
within each if
block. In these cases, or in cases where control will leave the method (exceptions), there is no difference between doing multiple if
statements and doing if-elseif-else
statements.
However, it's best practice to use if-elseif-else
anyhow. Suppose you change your code such that you don't do a return
in every if
block. Then, to remain efficient, you'd also have to change to an if-elseif-else
idiom. Having it be if-elseif-else
from the beginning saves you edits in the future, and is clearer to people reading your code (witness the misinterpretation I just gave you by doing a skim-over of your code!).
else vs return to use in a function to prematurely stop processing
I doubt the performance is going to be significantly different in either case. Like you I would tend to lean more toward the first method for readability.
In addition to the smaller indentation(which doesn't really matter much IMO), it precludes the necessity to read further for when your inputs == 0:
In the second method one might assume that there is additional processing after the if/else statement, whereas the first one makes it obvious that the method is complete upon that condition.
It really just comes down to personal preference though, you will see both methods used in practice.
Related Topics
How to "Properly" Print a List
How Can This Function Be Rewritten to Implement Ordereddict
Sqlite Insert Query Not Working with Python
Python Regex Escape Operator \ in Substitutions & Raw Strings
Scrape Website with Dynamic Mouseover Event
How to Run a Function Periodically in Python
Expected Conditions in Protractor
How to Automatically Fix an Invalid JSON String
Classification Using Movie Review Corpus in Nltk/Python
Advanced Nested List Comprehension Syntax
Why Is the Global Keyword Not Required in This Case
How to Get 2.X-Like Sorting Behaviour in Python 3.X
How to Check If One Two-Dimensional Numpy Array Contains a Specific Pattern of Values Inside It
Catching an Exception While Using a Python 'With' Statement
Runtimeerror: Main Thread Is Not in Main Loop
Python: Http Post a Large File with Streaming
Difference Between "Findall" and "Find_All" in Beautifulsoup
Why Do "Not a Number" Values Equal True When Cast as Boolean in Python/Numpy