For example:
for(int i = 0; i < 20 * 40 * 60 * 80; i++){ ... }
Compared to:
for(int i = 0; i < 3840000; i++){ ... }
The first loop runs much slower than the second (did some time-trials) even though the value of the conditional will never change at any stage throughout the iteration. Sure, with methods this would be different because that value may change (even though it probably shouldn’t). I was just wondering why Java doesn’t cache / temp that value.
long fact10 = factorial(10);
for(long n = 0; n < fact10; n++) vs for(long n = 0; n < factorial(10); n++)
Java cannot do the second optimization, because it does not know that
factorialis free of side effects. As far as the first benchmark goes, I am sure this is a mistake of some sort: Java compiler calculates the results of constant expressions at compile time, so the first two loops are equivalent.