简体   繁体   中英

Why is Math.max so expensive in Java?

I want to do the following

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

but that 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 already looked in the source code and all Java is doing is

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

也许是因为Java的Math类是第一次像任何其他Singleton或类似的东西一样被创建,因为在此之前没有人使用它,就像类加载器操作一样。

Method calls aren't free (even ignoring the potential class load that Roey pointed out): They involve pushing the arguments and a return address on the stack, jumping to a different location in the code, popping the arguments off the stack, doing the work, pushing the result on the stack, jumping back, and popping the result off the stack.

However , I suspect you'd find that if you had a Math.max call in a hotspot in your code (a place that was run a LOT ), Oracle's JVM's JIT would optimize it into an inline operation to speed it up. It won't bother if there doesn't seem to be any need, preferring speed of compilation of bytecode to machine code over optimization; but it's a two-stage compiler, where the second stage kicks in to more aggressively optimize hotspots it detects in the code.

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

This of course does not answer your question why your code is 'faster' now. Probably, it was not executed at all, because of dead code elimination, a compiler feature. Can you give us some surrounding code? Details about how often it is called is useful as well. Details about hardware also. Very important as well: Disable all power save features and all background tasks if you do 'measurements'. Best is to use something like JMH Cheers Benni

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM