Reputation: 15091
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:
$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). 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()
?
Upvotes: 1
Views: 66
Reputation: 533870
The JIT can inline and optimize away a method call, but only if it is relatively trivial e.g. a field lookup.
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. 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.
Upvotes: 2
Reputation: 13684
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?
Upvotes: 2