Wednesday, 15 July 2015

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



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

the question little bit ambiguous, these 2 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); }

they equivalent , should result in same bytecode representation. hence performance-wise, same.

if, else , break branch instructions. in case, break terminate loop , programme goes different branch. if status not met, branch taken, exactly same branch taken else.

example using javac compiler:

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

both , without else produce 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> homecoming :label3

java performance if-statement

No comments:

Post a Comment