Performance: greater / smaller than vs not equal to

前端 未结 7 1576
礼貌的吻别
礼貌的吻别 2020-12-14 14:47

I wonder if there is a difference in performance between

checking if a value is greater / smaller than another

for(int x = 0; x <         


        
7条回答
  •  天命终不由人
    2020-12-14 15:14

    Now 6 years later and after still receiving occasional notifications from this question I'd like to add some insights that I've gained during my computer science study.

    Putting the above statements into a small program and compiling it...

    public class Comp {
        public static void main(String[] args) {
            int y = 42;
    
            for(int x = 0; x < y; x++) {
                // stop if x >= y
            }
    
            for(int x = 0; x != y; x++) {
                // stop if x == y
            }
        }
    }
    

    ... we get the following bytecode:

      public static void main(java.lang.String[]);
        Code:
           // y = 42
           0: bipush        42  
           2: istore_1
    
           // first for-loop
           3: iconst_0
           4: istore_2
           5: iload_2
           6: iload_1
           7: if_icmpge     16      // jump out of loop if x => y
          10: iinc          2, 1
          13: goto          5
    
           // second for-loop
          16: iconst_0
          17: istore_2
          18: iload_2
          19: iload_1
          20: if_icmpeq     29      // jump out of loop if x == y
          23: iinc          2, 1
          26: goto          18
    
          29: return
    

    As we can see, on bytecode level both are handled in the same way and use a single bytecode instruction for the comparison.

    As already stated, how the bytecode is translated into assembler/machine code depends on the JVM. But generally this conditional jumps can be translated to some assembly code like this:

    ; condition of first loop
    CMP eax, ebx
    JGE label  ; jump if eax > ebx
    
    ; condition of second loop
    CMP eax, ebx
    JE  label  ; jump if eax == ebx
    

    On hardware level JGE and JE have the same complexity.

    So all in all: Regarding performance, both x < y and x != y are theoretically the same on hardware level and one isn't per se faster or slower than the other.

提交回复
热议问题