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?
Math pow () method in Java with Example. The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter. There are some special cases as listed below: If the second parameter is positive or negative zero...
public static double pow (double a, double b) Parameter : a : this parameter is the base b : this parameter is the exponent. Return : This method returns a b . Example 1: To show working of java.lang.Math.pow () method. Example 2: To show working of java.lang.Math.pow () method when argument is NaN.
Because Math.powis 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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With