"if" effectiveness conditions

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

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

 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 particular project, I really don't like readability, I know that the second is less readable)

+7
source share
3 answers

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

This means that if a is false , Java does not evaluate b , c , d , etc. since it already knows that the whole expression a && b && c && d && e && f && g will be false .

Thus, you cannot write your if as a series of nested if .

The only good way to optimize performance is to measure the performance of the program using the profiler, determine where the performance bottleneck is, and try to improve this part of the code. Optimization by checking the code and guessing, and then applying microoptimization is usually not an effective way of optimization.

+22
source

In addition to the other answers, even at 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 
+10
source

When profiling a program written in any language, do not focus on language structures, but rather focus on what your code does. Enter the code, find out where the time is spent, then you will know the reason, because it would be narrowed.

If you know that the slow parts of your program are in your if statement, then you already know the answer to your question.

I am posting this as an answer, because I believe that the question of the effectiveness of a particular language function for optimization purposes is a completely wrong approach, and I believe that you will benefit from a different strategy.

In addition, some implementations may handle things a little differently, therefore, if there is no stone in the standard standard (and sometimes that it is not a guarantee), the answer may be implementation dependent and conditional.

+6
source

All Articles