[英]When to create a new variable to store a value rather than calling function multiple times?
I once heard a difference between PHP and Java is in PHP the following is more efficient to store the return value of foo()
than call it each time the conditional statement of the loop is evaluated: 我曾经听说过PHP与Java之间的区别是PHP中,与每次在评估循环的条件语句时调用
foo()
相比,以下方法存储foo()
的返回值更为有效:
$x = 1;
for($y = 0; $y < foo($x); $y++)
{
//code goes here
}
vs 与
$x = 1;
$processed = foo($x);
for($y = 0; $y < $processed; $y++)
{
//code goes here
}
In Java when is it worth it to create a variable who is only used to test conditional statements (and value is never changed). 在Java中,何时创建一个仅用于测试条件语句的变量(值永远不会更改)是值得的。 For example in a project I'm working on now has
例如,在我正在从事的项目中,
int[] operator = new int[numberOfOperators(eqn)];
int[] numeric = new int[numberOfOperators(eqn) + 1];
for(int i = 0; i < operator.length; i++)
{
//code goes here
}
Will the Java Optimizer or JIT compiler know what to do with this or should I create a new variable that holds the return value of numberOfOperators()
? Java Optimizer或JIT编译器是否会知道该怎么做,还是应该创建一个保存
numberOfOperators()
返回值的新变量?
No, it will not 'cache' or something. 不,它不会“缓存”或其他东西。 How could the compiler even know, if on the next call of
numberOfOperators()
there will be the same or a different result? 如果在下一次调用
numberOfOperators()
会有相同或不同的结果,编译器怎么可能知道呢?
The JIT can inline and optimize away a method call, but only if it is relatively trivial eg a field lookup. JIT可以内联和优化掉方法调用,但前提是它相对来说比较琐碎,例如字段查找。
Before you try to optimise your code, you should run it through a CPU and/or memory profiler and when you have measured your performance then you can decide how to optimise your code. 在尝试优化代码之前,应先通过CPU和/或内存探查器运行它,然后在评估性能后可以决定如何优化代码。 Anything else will be just guessing what can make a difference.
其他任何事情都只是在猜测有什么作用。
In short, make the code clear and simple to understand and worry about performance when you know you have a problem because you measured it. 简而言之,当您知道自己有问题(因为已进行测量)时,使代码清晰易懂,并担心性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.