Is it faster to access a global or object variable?
In C++, I’m referring to the difference between
::foo
and
this->foo
In x86 assembler, this basically translates to
mov eax, offset foo
vs
mov eax, dword ptr[edx+foo]
All data in both cases is expected to be in cache.
(I know the difference if any will be tiny, and one should usually go with whichever makes the code simpler; but in this case there is literally no other difference, and the code in question will be called maybe half a billion times under a time limit, so I might as well go with whichever is even slightly faster.)
You need to test and time both.
However, do this knowing that you’ve made other decisions in your app that will have a greater performance impact by several orders of magnitude than this.
To human eyes the Global is faster to access, however what the compiler decides to put where, and how the processor decides to cache things will ultimately decide which is faster.
Test it and time it. I’d be stunned if you got meaningful differences in a non trivial app over millions of runs.