Reputation:
I was reading a book which says to use local variables to eliminate unnecessary memory references. For example, the code below is not very efficient:
int gsum; //global sum variable
void foo(int num) {
for (int i = 0; i < num; i++) {
gsum += i;
}
}
It is more efficient to have the code below:
void foo(int num) {
int fsum;
for (int i = 0; i < num; i++) {
fsum += i;
}
gsum = fsum;
}
I know the second case uses a local variable which is stored in a register. That's why it is a little bit faster while, in the first case, gsum
has to be retrieved from main memory too many times.
But I still have questions:
Q1- Isn't the the gcc compiler smart enough to detect it and implicitly use a register to store the global variable so that subsequent references will use the register exactly as the second case?
Q2- If, for some reason, the compiler is not able to optimize, then we still have the cache. Referencing a global variable from the cache is still very fast but I see that some programs which use local variables are 10 times faster than the ones who reference global variables. Why is this?
Upvotes: 2
Views: 189
Reputation: 6760
Q1: That register is probably going to be needed by other functions which will be called between subsequent calls to foo
. That means gsum
will need to be shuttled in and out of the register whenever this function is called.
Q2: It's possible that the page containing gsum
will stay in cache for a while. However, depending on what else your computer is doing, that page may get written to swap space in order to make room in memory for other pages.
Upvotes: 1