Why it is significantly slower to reference global variables in a for loop?
20:32 20 Oct 2020

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?

c optimization global-variables