Reputation: 904
Is there any difference in performance between:
public int method()
{
x = 1;
if (x == 0)
System.out.println("something");
return 1;
}
And
public int method()
{
x = 1;
if (x == 0)
System.out.println("something");
else
return 1;
return 7; //this won't happen because x is 1
}
As you can notice I used an else
in the second example. I do not know if the branching return is faster than the normal return.
Upvotes: 2
Views: 71
Reputation: 2129
let's see the jvm instructions :
the first method one if branch:
public int ifmethod();
0 aload_0 [this]
1 iconst_1
2 putfield ifperf.main.x : int [22]
5 aload_0 [this]
6 getfield ifperf.main.x : int [22]
9 ifne 20
12 getstatic java.lang.System.out : java.io.PrintStream [24]
15 ldc <String "something"> [30]
17 invokevirtual java.io.PrintStream.println(java.lang.String) : void [32]
20 iconst_1
21 ireturn
the second method with else branch :
public int ifelsemethod();
0 aload_0 [this]
1 iconst_1
2 putfield ifperf.main.x : int [22]
5 aload_0 [this]
6 getfield ifperf.main.x : int [22]
9 ifne 23
12 getstatic java.lang.System.out : java.io.PrintStream [24]
15 ldc <String "something"> [30]
17 invokevirtual java.io.PrintStream.println(java.lang.String) : void [32]
20 goto 25
23 iconst_1
24 ireturn
25 bipush 7
27 ireturn
As you can see the both method are stricly identic in that case. the answer is at line 9 you have the test ifne ("IF Not Equal goto line XY") so in one case you go at line 20 and in the second at line 23. and then you execute the exact same instruction.
So in one case you will execute 0-9 -> 20,21 and in the other 0-9->23,24
Upvotes: 3