If (condition) else or if (condition), is there a performance difference when using break?
The question is a bit ambiguous, these two equivalents in assembly / performance code are wise:
public void example{
do{
//some statements;
if(condition) break;
//some statements;
}while(true);
}
against
public void example{
do{
//some statements;
if(condition){
break;
}else{
//some statements;
}
}while(true);
}
source to share
They are equivalent and they should result in the same bytecode representation. Therefore, in terms of performance, they are the same.
if
, else
and break
are branch instructions. In this case, the break
loop will end and the program will branch to another branch. If the condition is not met, another branch is taken, which is exactly the same branch made else
.
An example of using the compiler javac
:
int a = System.in.read();
do {
System.out.println("a");
if (a > 0) {
break;
} else {
System.out.println("b");
}
} while (true);
Both and without 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
source to share