Is it more efficient to access an array each time I use a variable, or to create a temporary variable and set it to the array:
For example:
int A; int B; ...etc... int Z;
int *ints = [1000 ints in here];
for (int i = 0; i < 1000; i++) {
A = ints[i];
B = ints[i];
C = ints[i];
...etc...
Z = ints[i];
}
or
int A; int B; ...etc... int Z;
int *ints = [1000 ints in here];
for (int i = 0; i < 1000; i++) {
int temp = ints[i];
A = temp;
B = temp;
C = temp;
...etc...
Z = temp;
}
Yes, this is not something I want to do, but it is the easiest example I could think of.
So which for loop would be quicker at using the array?
It doesn’t matter; the compiler will most likely produce the same code in both cases (unless you have disabled all optimizations). (The generated assembly code will likely resemble the second example – first, the array element will be loaded into a register, and then, the register will be used whenever the array element is needed.) Go with the style you find to be most readable and least prone to errors (which is probably the latter style, which avoids repeating the index).
(This assumes that you don’t have any threads or volatile variables, so that the array element is guaranteed not to change in the course of a loop iteration.)