Consider the following code:
public void doSomething(Foo foo) {
for (int i = 0; i < factorial(foo.getSize()); i++) {
//...
}
}
public void doSomethingAnotherWay(Foo foo) {
int max = factorial(foo.getSize());
for (int i = 0; i < max; i++) {
//...
}
}
public static int factorial(int n) {
//...
}
At a first glance, in the function doSomething the factorial function (or whatever other function takes its place) is evaluated several times whereas it is only evaluated once in the function doSomethingAnotherWay. Suppose the factorial function is expensive to compute.
Would it be worthwhile to store its result in a variable before the loop or is this something that the compiler would optimize anyways?
Does the factorial function have to be static for this optimization to occur (because then its output is always determined by its input)? What if foo.getSize() can change (via a setter, for example)? How would optimizations like this work in general?