(int) Math.sqrt(n) much slower than (int) Math.floor(Math.sqrt(n))

Peter Perháč picture Peter Perháč · Nov 28, 2013 · Viewed 16.9k times · Source

I was looking at my code, hoping to improve its performance and then i saw this:

int sqrt = (int) Math.floor(Math.sqrt(n));

Oh, ok, i don't really need the call to Math.floor, as casting the double returned from Math.sqrt(n) will be effectively flooring the number too (as sqrt will never return a negative number). So i went and dropped the call to Math.floor:

int sqrt = (int) Math.sqrt(n)

sat back and complacently watched the code run and perform roughly 10% ! worse than its previous version. This came to me as a shock. Any ideas anyone?

Math.floor javadocs: "Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer."

EDIT in my case n is a long. Any chance cast-floor-sqrt would ever produce a different int than cast-sqrt? I personally can't see why it ever would... all numbers involved are positive.

Answer

mvieghofer picture mvieghofer · Nov 28, 2013

The Math.floor method just delegates the call to the StrictMath.floor method (see here). This method is a native method. After this method the cast does not have to do anything because it is already a number that is equal to an integer (so no decimal places).

Maybe the native implementation of floor is faster than the cast of a double value to an int value.