When you have code like this (written in java, but applicable to any similar language):
public static void main(String[] args) {
int total = 0;
for (int i = 0; i < 50; i++)
total += i * doStuff(i % 2);
}
public static int doStuff(int i) {
}
You can see that there is room for improvement. doStuff(i % 2)returns only two different values: one for doStuff(0)odd numbers and one doStuff(1)for odd numbers. Therefore, you spend a lot of time calculating / power recalculating these values every time you say doStuff(i % 2). You can improve this:
public static void main(String[] args) {
int total = 0;
boolean[] alreadyCalculated = new boolean[2];
int[] results = new int[2];
for (int i = 0; i < 50; i++) {
if (!alreadyCalculated[i % 2]) {
results[i % 2] = doStuff(i % 2);
alreadyCalculated[i % 2] = true;
}
total += i * results[i % 2];
}
}
Now it accesses the stored value, not the recalculation. It might seem silly to keep such arrays, but for cases like a loop, say i = 0, i < 500, and you check i % 32every time, or something like that, an array is an elegant approach.
? , .