Java – what is the difference between putting the most likely real conditions in if, else if, or else
Is there any difference in putting the most likely conditions in if, else if, or else conditions
For example:
int[] a = {2,4,6,9,10,30,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 between execution time and input
int[] a = {3,8,7,0}
Solution
In fact, Java's answer is "it depends on"
You can see that when you run java code, the JVM starts using the interpreter when collecting statistics One of the statistics that can be recorded is which paths are most commonly used in branch instructions The JIT compiler can then use these statistics to affect code reordering, which does not change the semantics of the compiled code
Therefore, if you want to execute code using two different data sets, that is, most are zero and most are non-zero, the JIT compiler may compile the code in different ways
Whether it can actually do this optimization depends on whether it can determine whether the reordering is effective For example, can it infer that the conditions being tested are mutually exclusive?
So how does this affect complexity? Well... Let's summarize the simplified example by assuming that the JIT compiler does nothing "smart" And suppose we don't just deal with arrays of length 10 (which makes the discussion of complexity meaningless)
Think about it:
>For each zero, cycle through one test and one increment – say, two operations. > For each non-zero element, the loop performs two tests and one increment – for example, three operations
Therefore, when all zero to 3 * n operations are non-zero, there are about 2 * n operations for n elements But both are o (n)... So the complexity of big O is not affected
(well, I left something... But you got the picture. One of the cases will be faster, but the complexity will not be affected.)