Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`if` condition efficiency

I'm working on improving the performance of a Java program. After I've improved the data structures and the algorithm's complexity, I'm trying to improve the implementation. I want to know if it really matters how I use the if statement in condition.

Does the compiler treat these two versions the same? Do they cost the same (If I have much more variables inside the if statement)?

if(a && b && c && d && e && f && g)

OR

if(a)
 if(b)
  if(c)
   if(d)
    if(e)
     if(f)
      if(g)

(In this specific project I don't really care about readability, I know the second is less readable)

like image 392
Maroun Avatar asked Nov 29 '12 13:11

Maroun


2 Answers

The && operator (and also ||) is a short-circuit operator in Java.

That means that if a is false, Java doesn't evaluate b, c, d etc., because it already knows the whole expression a && b && c && d && e && f && g is going to be false.

So there is nothing to be gained to write your if as a series of nested if statements.

The only good way to optimize for performance is by measuring the performance of a program using a profiler, determining where the actual performance bottleneck is, and trying to improve that part of the code. Optimizing by inspecting code and guessing, and then applying micro-optimizations, is usually not an effective way of optimizing.

like image 175
Jesper Avatar answered Oct 16 '22 01:10

Jesper


In addition to the other answers, even on a very low level there is no difference between the two approaches - they are compiled into the same bytecode:

boolean a=true, b=true, c=true, d=true, e=true, f=true, g=true;
   0: iconst_1
   1: istore_1
   2: iconst_1
   3: istore_2
   4: iconst_1
   5: istore_3
   6: iconst_1
   7: istore        4
   9: iconst_1
  10: istore        5
  12: iconst_1
  13: istore        6
  15: iconst_1
  16: istore        7

if(a && b && c && d && e && f && g) {}
  18: iload_1
  19: ifeq          45
  22: iload_2
  23: ifeq          45
  26: iload_3
  27: ifeq          45
  30: iload         4
  32: ifeq          45
  35: iload         5
  37: ifeq          45
  40: iload         6
  42: ifeq          45

if(a) if(b) if(c) if(d) if(e) if(f) if(g) {}
  45: iload_1
  46: ifeq          72
  49: iload_2
  50: ifeq          72
  53: iload_3
  54: ifeq          72
  57: iload         4
  59: ifeq          72
  62: iload         5
  64: ifeq          72
  67: iload         6
  69: ifeq          72
like image 21
Andreas Fester Avatar answered Oct 16 '22 00:10

Andreas Fester