Search code examples
javatime-complexityexecution

What is the different in putting most possible true condition in if, else-if or else


Is there is any difference to put most probable condition in if, else-if or else condition

Ex :

int[] a = {2,4,6,9,10,0,30,0,31,66}
int firstCase = 0, secondCase = 0, thirdCase = 0;
for( int i=0;i<10;i++ ){
    int m = a[i] % 5;
    if(m < 3) {
        firstCase++;
    } else if(m == 3) {
        secondCase++;
    } else {
        thirdCase++;
    }
}

What is the difference of the execution time with input

int[] a = {3,6,8,7,0,0,0,0,0,0}

Solution

  • Is there is any different to put most possible true condition in if, else-if or else condition

    Actually, the answer with Java is that "it depends".

    You see, when you run Java code, the JVM starts out by using the using the interpreter while gathering statistics. One of the statistics that may be recorded is which of the paths in a branch instruction is most often taken. These statistics could then used by the JIT compiler to influence code reordering, where this does not alter the compiled code's semantics.

    So if you were to execute your code, with two different datasets (i.e. "mostly zero" and "mostly non-zero"), it is possible that the JIT compiler would compile the code differently.

    Whether it can actually make this optimization depends on whether it can figure out that the reordering is valid. For example, can it deduce that the conditions being tested are mutually exclusive?


    So how does this affect the complexity? Well ... lets do the sums for your simplified example, assuming that the JIT compiler doesn't do anything "smart". And assume that we are not just dealing with arrays of length 10 (which renders the discussion of complexity moot).

    Consider this:

    • For each zero, the loop does one test and one increment - say 2 operations.

    • For each non-zero element, the loop does two tests and one increment - say 3 operations.

    So that is roughly 2N operations for N elements when all zero versus 3N operations when all non-zero. But both are O(N) ... so the Big O complexity is not affected.

    (OK I left some stuff out ... but you get the picture. One of the cases is going to be faster, but the complexity is not affected.)