Quickly square a double
Squaring by multipling with self is the fastest. Because that approch can be directly translated into simple, non-branching bytecode (and thus, indirectly, machine code).
Math.pow()
is a quite complex function that comes with various guarantees for edge cases. And it need to be called instead of being inlined.
The fastest way to square a number is to multiply it by itself.
Why is
Math.pow
so slow?
It's really not, but it is performing exponentiation instead of simple multiplication.
and why does it cope badly with > 1 and even worse with < -1 numbers
First, because it does the math. From the Javadoc it also contains tests for many corner cases. Finally, I would not rely too much on your micro-benchmark.