Global Variables performance effect (c, c++)

后端 未结 4 649
半阙折子戏
半阙折子戏 2021-02-05 08:24

I\'m currently developing a very fast algorithm, with one part of it being an extremely fast scanner and statistics function. In this quest, i\'m after any performance benefit.

4条回答
  •  暖寄归人
    2021-02-05 08:58

    It really depends on your compiler, platform, and other details. However, I can describe one scenario where global variables are faster.

    In many cases, a global variable is at a fixed offset. This allows the generated instructions to simply use that address directly. (Something along the lines of MOV AX,[MyVar].)

    However, if you have a variable that's relative to the current stack pointer or a member of a class or array, some math is required to take the address of the array and determine the address of the actual variable.

    Obviously, if you need to place some sort of mutex on your global variable in order to keep it thread-safe, then you'll almost certainly more than lose any performance gain.

提交回复
热议问题