0

I'm comparing int a and int b. Is there any performance difference between if(a>=b){...} vs
if(a==b || a>b){...}? Thanks

elmoz
  • 13
  • 1
  • If anything, the latter might be slower because it has multiple comparisons vs. just the one, though I think the engine will optimize that bit. You could always use `if (!a – Erik S Mar 26 '15 at 22:40
  • Your question does not make any practical sense, since Java code optimizer will select the best representation for both. – PM 77-1 Mar 26 '15 at 22:40
  • 2
    Premature optimization is just a waste of time. – PM 77-1 Mar 26 '15 at 22:41
  • It's a slippery slope to start sweating the small stuff like this. – Fluffmeister General Mar 26 '15 at 22:41
  • Hm, I actually read Javascript first, then it might've been an issue. In the case of Java, where your code is actually compiled, it'll definitely optimize it by itself, thus it doesn't make a difference. – Erik S Mar 26 '15 at 22:41
  • (On premature optimization: http://c2.com/cgi/wiki?PrematureOptimization) – Erik S Mar 26 '15 at 22:42
  • I'm aware it's premature, just curious about what's going on at a lower level. – elmoz Mar 26 '15 at 22:58

1 Answers1

0

You can always look at the byte code to see what's a happening at a lower level. This doesn't mean all compilers / options will do it the same, but I suppose the important one is the one you are using. Also, while it's a lower level, it's not the lowest level. As mentioned elsewhere on this site "Optimization in Java is mostly done by the JIT compiler at runtime". So in the end you can't avoid some leap of faith that Java will do the smart thing for you in cases like this.

int foo(int a, int b) {
    if (a == b || a > b) return 1;
    return 0;
}

int bar(int a, int b) {
    if (a >= b) return 1;
    return 0;
}

Using javap -c on the class file you can see:

int foo(int, int);
Code:
   0: iload_1       
   1: iload_2       
   2: if_icmpeq     10
   5: iload_1       
   6: iload_2       
   7: if_icmple     12
  10: iconst_1      
  11: ireturn       
  12: iconst_0      
  13: ireturn       

int bar(int, int);
Code:
   0: iload_1       
   1: iload_2       
   2: if_icmplt     7
   5: iconst_1      
   6: ireturn       
   7: iconst_0      
   8: ireturn       
Community
  • 1
  • 1
jas
  • 10,715
  • 2
  • 30
  • 41