Joop
Joop

Reputation: 3788

If(condition) else or if(condition), is there a difference in performance when using break?

The question is a little bit ambiguous, are these two equivalent in assembly code/performance wise:

public void example{
  do{
     //some statements;
     if(condition) break;
     //some statements;
  }while(true);
}

versus:

public void example{
  do{
     //some statements;
     if(condition){ 
     break;
     }else{
     //some statements;
     }
  }while(true);
}

Upvotes: 3

Views: 101

Answers (1)

M A
M A

Reputation: 72844

They are equivalent and they should result in the same bytecode representation. Therefore performance-wise, they are the same.

if, else and break are branch instructions. In this case, break would terminate the loop and the program goes to a different branch. If the condition is not met, another branch is taken, which is exactly the same branch taken by the else.

Example using the javac compiler:

int a = System.in.read();
do {
    System.out.println("a");
    if (a > 0) {
        break;
    } else {
        System.out.println("b");
    }
} while (true);

Both this and without the else produce the following:

getstatic java/lang/System/in Ljava/io/InputStream;
invokevirtual java/io/InputStream/read()I
istore_1
getstatic java/lang/System/out Ljava/io/PrintStream;            :label1
ldc "a"
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
iload_1
ifle <label2>
goto <label3>
getstatic java/lang/System/out Ljava/io/PrintStream;            :label2
ldc "b"
invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V
goto <label1>
return                                                          :label3

Upvotes: 4

Related Questions