Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x*x vs Math.pow(x,2) java performance

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?

like image 831
Tomáš Mocek Avatar asked Mar 19 '15 12:03

Tomáš Mocek


People also ask

How to use math POW () method in Java?

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...

What is the return type of double POW () method in Java?

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.

Why does JVM replace a call with exactly x*x when exponent is 2?

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.


2 Answers

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

like image 168
apangin Avatar answered Oct 04 '22 02:10

apangin


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.

like image 44
Davide Lorenzo MARINO Avatar answered Oct 04 '22 02:10

Davide Lorenzo MARINO