2

I was implementing a snippet on Leetcode and my initial loop ran like this:

    //n and x are an integer and a double respectively
    long N = Math.abs((long)n);
    double result = 1;
    while(N != 0){
        if((N & 1) == 1){
            result *= x;
        }
        N = N >> 1;
        x *= x;
    }

The whole code took 2ms to run. I then changed N != 0 to N > 0 and the code took 1ms to run. Why was there a jump in runtime due to this change? In other words, how does Java implement x != y and x > y?

Balaji R
  • 61
  • 1
  • 4
  • 2
    Did you test it just once? There will be time differences between each execution and the result ins´t really saying that there are major differences in terms of performance. It´s just a standard "this time it took x ms", next time it might be vica verse. – SomeJavaGuy Aug 11 '16 at 07:01
  • 1
    I think the flaw may be in your test... – Adriano Repetti Aug 11 '16 at 07:02
  • 1
    Writing [micro-benchmarks in Java](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java/513259) is a lot harder than you think. Your measurement is not as precise as you think. – Jesper Aug 11 '16 at 07:10
  • Kevin is right. After running a lot more tests it looks like the runtime for both wavers between 1ms and 2ms. I think Leetcode provides the ceiling of the runtime as the official runtime and the actual runtimes must have been hovering somewhere around 1ms (so the 1ms and 2ms). Thanks! – Balaji R Aug 11 '16 at 07:14

1 Answers1

-1

Probably because when jvm checks for N > 0 it looks just for byte that represents sign and when jvm checks for N != 0 it needs to go through all bytes in the variable.

Montreal
  • 2,143
  • 5
  • 18
  • 28
  • 1
    Given that nowadays all operations are in 64 bits together and bytes are not loaded individually to the CPU, what you are describing is probably not applicable these days. – RealSkeptic Aug 11 '16 at 07:17
  • Difference can be in comparing one byte and comparing `n` bytes. Even if they all loaded in CPU in one time, they still need to be checked and that can make a difference in time measures. – Montreal Aug 11 '16 at 07:23
  • 1
    Neither operation will take more than one clock cycle - it's a single machine instruction (on an IA-64). The difference doesn't really exist, the OP noticed that himself. – RealSkeptic Aug 11 '16 at 10:01