C++ performance of global variables

前端 未结 9 1779
谎友^
谎友^ 2021-01-04 07:32

For clarification: I know how evil globals are and when not to use them :)

  • Is there any performance penalty when accessing/setting a global variable vs. a loca
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 07:42

    The answer is tied to the overall structure of the program.

    For example, I just disassembled this, and in both cases the looping variable was moved into a register, after which there was no difference:

    int n = 9;
    int main()
    {
        for (n = 0; n < 10; ++n)
            printf("%d", n);
    
        for (int r = 0; r < 10; ++r)
            printf("%d", r);
    
        return 0;
    }
    

    Just to be sure, I did similar things with classes and again saw no difference. But if the global is in a different compilation unit that might change.

提交回复
热议问题