Why is Math.max so expensive in Java?

I want to do the following

int sum = x+y;
sum = Math.max(sum,x);

      

but this line of code tends to take longer than

int sum = x+y;
if(x>sum)sum=x;

      

I hope this is not inappropriate to ask, but can someone explain why this is?

I have looked at the source code already and all Java does is

return (a >= b) ? a : b;

      

+3


source to share


3 answers


Maybe because Java Math

class is being created for the first time, like any other Singleton or something like that, because nobody used it as a classloader operation before.



+9


source


Method calls are not free (even ignoring the potential class load that Roy pointed out): they include pushing arguments and return addresses on the stack, going elsewhere in code, poping arguments off the stack, doing work, pushing the result onto the stack by bouncing back and popping the result from the stack.



However , I suspect that you will find that if you had a call Math.max

in a hot spot in your code (the place where the LOT was started ), the Oracle JVM JIT would optimize it in an inline operation to speed it up. This will not bother you if there is no need, preferring the compilation speed of bytecode to machine optimized code; but this is a two-step compiler where the second step is run to more aggressively optimize the hotspots it finds in the code.

+3


source


microbenchmarking in Java is very hard work in general. The example and statement cannot be generalized and, as usual, the answer to your question "depends on that".;). First of all, the source code you see in the JDK implementation for Math.max is the default, which is not used at all on modern hardware. The compiler replaces this call with a CPU operation. More details here .

This, of course, does not answer your question as to why your code is "faster" now. It was probably not executed at all, due to the elimination of dead code, a compiler function. Can you give us the environment code? Information on how often it is called is also helpful. Hardware details also. VERY IMPORTANT: Disable all power saving features and all background tasks if you perform "measurements". Your best bet is to use something like JMH Cheers Benni

0


source







All Articles