Reputation: 398
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?
Upvotes: 12
Views: 10316
Reputation: 98640
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
.
Upvotes: 55
Reputation: 26956
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.
Upvotes: 2
Reputation: 73578
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.
Upvotes: -2