简体   繁体   中英

Why it is significantly slower to reference global variables in a for loop?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM