Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: if-return-if-return vs if-return-elseif-return

Asked an unrelated question where I had code like this:

public boolean equals(Object obj) {     if (this == obj)         return true;      if (obj == null)         return false;      if (getClass() != obj.getClass())         return false;      // Check property values } 

I got a comment which claimed that this was not optimal, and that it instead (if I understood correctly) should do this:

public boolean equals(Object obj) {     if (this == obj)         return true;      else if (obj == null)         return false;      else if (getClass() != obj.getClass())         return false;      // Check property values } 

Because of the return statements, I can't really see why any of them should be more efficient or faster than the other. Given a certain object, both methods would have to do an equal number of checks as far as I can see. And because of the return statements, no extra code would run in any of them.

Am I missing something here? Is there something to it? Are there some compiler optimizations or something going on or whatever?

I know this is micro optimization and I will most likely stick with the first either way, since I think it looks cleaner with all the ifs on the same position. But I can't help it; I'm curious!

like image 263
Svish Avatar asked Apr 14 '11 12:04

Svish


People also ask

Which is better if else or if return?

They are equally efficient, but B is usually considered to give better readability, especially when used to eliminate several nested conditions.

What does return do in IF statement Java?

The return here is probably used in order to "improve" the performance of the method, so that other comparisons are not executed, once the needed scenario is performed.

Can I use if and else if without else in Java?

In most cases you want to use if() block without any else . Sometimes you need else . Very seldom you need if/else if .

Is else return necessary?

Don't put an else right after a return. Delete the else, it's unnecessary and increases indentation level.


1 Answers

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.

like image 67
Joachim Sauer Avatar answered Sep 19 '22 21:09

Joachim Sauer