performance by creating new variable

狂风中的少年 提交于 2019-12-06 16:43:23

The first will theoretically be faster.

In the second, the JVM will not only calculate a-b twice, but will also temporarily assign storage for the result twice before passing it to the two method calls.

I just ran tests for these cases 100 million times and came up with just 10-15ms difference between them with the first being faster. My test results will be skewed because a and b are constants, but it nevertheless seems to confirm the theory.

Vladimir Ivanov

Simply measure the time. Without knowing the facts you can't do any conclusions. See this question about the tools.

If the difference is hard to notice, always prefer the well readable code.

The JVM may optimise the code in the second case to act like the first. However if it doesn't it may cost you 1 clock cycle which might be about 3 ms (if you call it 9 million times on a 3 GHz processor)

I prefer the first form because it reduces repetition which for me makes it easier to read. If your expression is more expensive, it could make more of a difference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!