简体   繁体   English

为什么Math.max在Java中如此昂贵?

[英]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 我已经查看了源代码,所有Java都在做

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. 方法调用不是免费的(甚至忽略了Roey指出的潜在类加载):它们涉及在堆栈上推送参数和返回地址,跳转到代码中的不同位置,从堆栈中弹出参数,执行工作,将结果推到堆栈上,跳回来,然后将结果弹出堆栈。

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. 但是 ,我怀疑你会发现如果你的代码中的热点中有一个Math.max调用(一个运行很多的地方),Oracle的JVM的JIT会将其优化为内联操作以加速它。 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. Java中的微基准测试通常是一项非常艰苦的工作。 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. 首先,您在Math.max的JDK实现中看到的源代码是默认值,在现代硬件上根本不使用。 The compiler replaces this call with a CPU operation. 编译器用CPU操作替换此调用。 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 最好是使用像JMH Cheers Benni这样的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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