Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Circuiting vs Multiple if's

What are the differences between this:

if(a && b)
{
     //code
}

and this:

if(a)
{
     if(b)
     {
          //code
     }
}

From what I know b will only get evaluated in the first code block if a is true, and the second code block would be the same thing.

Are there any benefits of using one over the other? Code execution time? memory? etc.

like image 514
Aequitas Avatar asked Dec 14 '22 13:12

Aequitas


2 Answers

They get compiled to the same bytecode. No performance difference.

Readability is the only difference. As a huge generalization, short-circuiting looks better but nesting is slightly clearer. It really boils down to the specific use case. I'd typically short-circuit.


I tried this out. Here's the code:

public class Test {

    public static void main(String[] args) {
        boolean a = 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 this 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.

like image 80
Anubian Noob Avatar answered Dec 17 '22 02:12

Anubian Noob


It makes a difference if you have an else associated with each if.

if(a && b)
{
     //do something if both a and b evaluate to true
} else {
    //do something if either of a or b is false
}

and this:

if(a)
{
     if(b)
     {
          //do something if both a and b are true
     } else {
          //do something if only a is true
     }
} else {
     if(b)
     {
          //do something if only b is true
     } else {
          //do something if both a and b are false
     }
}
like image 22
JavaHopper Avatar answered Dec 17 '22 03:12

JavaHopper