12

I have done some testing about whether x*x or Math.pow(x, 2) is faster in Java. I was expecting simple x*x to be somewhat faster, however, it turned out that its about equally fast. Can someone enlighten me, how is that possible, please?

Neuron
  • 5,141
  • 5
  • 38
  • 59
Tomáš Mocek
  • 398
  • 3
  • 14
  • 5
    How exactly did you test this? Writing micro-benchmarks is much harder than you think: [How do I write a correct micro-benchmark in Java?](http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java) – Jesper Mar 19 '15 at 12:21
  • why dont you try `x*x*x*x` vs `Math.pow(x,4)`, you might get the answer – Naeem Shaikh Mar 19 '15 at 12:21
  • I tested it by running the same operation in a loop and measuring time by System.currenttimemillis() function – Tomáš Mocek Mar 19 '15 at 12:27
  • Yea i tried x*x*x and so on, which is getting faster then function, however, i am interested in this particular situation. – Tomáš Mocek Mar 19 '15 at 12:28

3 Answers3

55

how is that possible, please

Because Math.pow is JVM intrinsic, that is, JIT-compiler inlines the call. Furthermore, when it sees that exponent is a constant 2, it replaces the call with exactly x*x.

Proof from HotSpot sources

apangin
  • 92,924
  • 10
  • 193
  • 247
2

The internal implementation of Math.pow() is delegated to a native function so it could be reasonable for a good performance. In any case to have valid test results you have to test the time in a loop to have an execution time realistic.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
-2

For all you know it's JITted (or even already in compile-time) down to the same exact thing. These kinds of micro-benchmarks rarely give very usable results, since there is no real context.

It's definitely not a reason to prefer one over another, since real world code rarely has a simple x^2 operation as a performance hotspot.

Kayaman
  • 72,141
  • 5
  • 83
  • 121