3

On a 64-bit OS with an i5-3570k, this piece of code takes 1.19 seconds on average to execute:

for (int i = 0; i < 1e9; i++);

If 1e9 is replaced with 1000000000 or (int)1e9, it only takes 0.0013 seconds on average to execute.

To me, it's fairly intuitive that comparing doubles is slower, when taken into consideration that doubles are more complex and take up double the memory of ints, but why is it so much slower?

Dabble
  • 182
  • 1
  • 3
  • 14
  • 5
    http://stackoverflow.com/questions/19844048/why-is-long-slower-than-int-in-x64-java?rq=1 – Sotirios Delimanolis Nov 20 '15 at 22:59
  • 2
    The answer in short: The JVM uses loop unrolling with the ints to optimize the loop when using ints, but not when using longs (or doubles it looks like in your case!). So it's not that int vs. long/doubles are slower, rather ints are optimized by the JVM in the case of this loop example. You can replicate the results I believe if you unrolled the loop yourself when using doubles – Lucas Crawford Nov 20 '15 at 23:06
  • Mind you, "unrolling" this loop would just mean changing `i++` to `i+=16`, since it has no content. – RealSkeptic Nov 20 '15 at 23:09
  • Not sure how aggressive the JVM is at optimizations, but the `int` version might not be executed at all and the timing might just be including auxiliary times like JIT compilation. A compiler that can unroll loops should be able to easily see that this case makes no modifications to memory used subsequently -- though it's funny that it can't do that for longs or doubles (not the unrolling part but just eliminating the entire loop as a result of not having any side relevant effects). –  Nov 20 '15 at 23:28
  • 1
    @Ike if you put some code within the loop (e.g. just count up some variable, which you output after it), the result is still the same. You can tell the JVM to tell you about OSR-compilations by calling it with `-XX:+PrintCompilation`. – Turing85 Nov 20 '15 at 23:48
  • Oh I see -- not quite as aggressive at optimizations as I thought. I'm used to those aggressive optimizers that would easily skip the entirety of that loop unless you actually did that. On the plus side, that should make benchmarking a lot easier to do in Java. –  Nov 21 '15 at 04:59

0 Answers0