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.)
The compiler is smart enough to realize that these are equivalent and will produce the same code. You should therefore write it in the most understandable way for future people reading your code.
As Aasmund's answer states, there is likely no performance difference since the compiler will treat both in the same way. However, you might find assigning to a temporary variable gives improved code readability, and if in the future you want to use ints[i+1]
throughout the loop you will only need to change one line rather than many. Never call a variable "temp" though, give it a useful name like currentInt
.
精彩评论