通过创建新变量来提高性能 [英] performance by creating new variable

查看:124
本文介绍了通过创建新变量来提高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尽可能地以性能编写我的Java程序,以便减少所有内容以使其具有最佳性能...在程序中,一种方法称为apprx. 900万次.在那里,我必须计算东西,只需减去两个整数,则需要两次. 所以我的问题是,更快的方法是:使用计算结果初始化新的整数,或者只计算两次值? 例如:

i want to write my java programm as performant as i can so i'm reducing everything to have best performance... In the programm a method will called apprx. 9million times. there i have to calculate somthing, just subtracting two integers and these are needed twice. so my question is, what is faster: initialize new integer with the result of calculation or just calculate the values twice? e.g:

int result = a-b;
methodToCall(result, foo, bla);
otherMethod(result, bla, foo);

methodToCall(a-b, foo, bla);
otherMethod(a-b, bla foo);

我看不到直接的区别,但是有时第一种方法的区别要快一点... 总的来说:第一种方法总是更好吗?例如,当使用其他类型的计算时(更复杂). Java编译器或jvm是否正在对其进行优化以使其更优化,例如看到我两次执行相同的计算,并且只执行一次,并且自己缓存了结果吗?

i cant see a difference directly, but sometimes its with the first method a little bit faster... in general: is the first method always better? e.g when using other types of calculation (more complex). Is the java compiler or the jvm doing something with it to optimize it, e.g. see that i do the same calculation twice and doing it only once and cache the result by its own?

推荐答案

第一个将从理论上讲会更快.

在第二个中,JVM不仅会计算两次a-b,还将在两次将结果传递给两个方法调用之前为结果临时分配存储两次.

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.

我刚刚对这些案例进行了1亿次测试,结果发现它们之间只有10-15毫秒的差异,第一个更快.我的测试结果会偏斜,因为a和b是常数,但这似乎证实了这一理论.

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.

这篇关于通过创建新变量来提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆