java - Short Circuiting vs Multiple if's -
what differences between this:
if(a && b) { //code }
and this:
if(a) { if(b) { //code } }
from know b
evaluated in first code block if a
true, , second code block same thing.
are there benefits of using 1 on other? code execution time? memory? etc.
they compiled same bytecode. no performance difference.
readability difference. huge generalization, short-circuiting looks better nesting clearer. boils down specific use case. i'd typically short-circuit.
i tried out. here's code:
public class test { public static void main(string[] args) { boolean = 1>0; boolean b = 0>1; if (a && b) system.out.println(5); if (a) if (b) system.out.println(5); } }
this compiles to:
0: iconst_1 1: istore_1 2: iconst_0 3: istore_2 4: iload_1 5: ifeq 19 8: iload_2 9: ifeq 19 12: getstatic #2 15: iconst_5 16: invokevirtual #3 19: iload_1 20: ifeq 34 23: iload_2 24: ifeq 34 27: getstatic #2 30: iconst_5 31: invokevirtual #3 34: return
note how block repeats twice:
4: iload_1 5: ifeq 19 8: iload_2 9: ifeq 19 12: getstatic #2 15: iconst_5 16: invokevirtual #3
same bytecode both times.
Comments
Post a Comment