Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: is including an else here faster? Or better practice?

In situations such as the one in the java snippet below, is it faster or better practice to surround the return false with an else block compared to having it just after the else block?

public boolean test(boolean var){
    if (var == true){
        return true;
    }
    return false;
}

compared to

public boolean test(boolean var){
    if (var == true){
        return true;
    }else{
        return false;
    }
}

Obviously this is an extremely simple example which can be shortened to one line, but my question is whether there is a jvm optimization which makes it more efficient to use the else block in the second snippet, or if it's better practice since both snippets are logically equivalent. So far, I have been using the first snippet simply because there's a little less code.

like image 233
zalpha314 Avatar asked Dec 01 '22 00:12

zalpha314


1 Answers

I compiled both examples and the resulting bytecodes are identical:

  public boolean test(boolean var);
    0  iload_1 [var]
    1  ifeq 6
    4  iconst_1
    5  ireturn
    6  iconst_0
    7  ireturn
      Line numbers:
        [pc: 0, line: 5]
        [pc: 4, line: 6]
        [pc: 6, line: 8]
      Local variable table:
        [pc: 0, pc: 8] local: this index: 0 type: scratch.Else1
        [pc: 0, pc: 8] local: var index: 1 type: boolean

  public boolean test(boolean var);
    0  iload_1 [var]
    1  ifeq 6
    4  iconst_1
    5  ireturn
    6  iconst_0
    7  ireturn
      Line numbers:
        [pc: 0, line: 5]
        [pc: 4, line: 6]
        [pc: 6, line: 8]
      Local variable table:
        [pc: 0, pc: 8] local: this index: 0 type: scratch.Else2
        [pc: 0, pc: 8] local: var index: 1 type: boolean

As for which one you should use? In this contrived example, the answer is a resounding NEITHER. The best code that matches the behavior is this:

public boolean test(boolean var){
    return var;
}

Given the choices of "if { return } else { return }" vs. "if { return } return", my answer is usual the latter because I prefer less indentation. But I think it really depends on how much code is in each branch. More else code points to the latter, more if code points to the former.

like image 177
Chris Dolan Avatar answered Dec 14 '22 11:12

Chris Dolan