0

I wonder if having too many global variables in Lua would slow down when accessing a global variable.

For example, if my program has 10,000 global variables, would this be slower to call a global function A than calling the function in a program that has only 100 global variables?

How does Lua find a registered global variable? Does it use some kind of hash map?

Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • 1
    Possible duplicate of [Global Variables performance effect (c, c++)](https://stackoverflow.com/questions/5210787/global-variables-performance-effect-c-c) – TehMattGR Jul 06 '19 at 15:26
  • 3
    @TehMattGR My question is about Lua not c, c++ so it's not a duplicate. – Zack Lee Jul 06 '19 at 15:28
  • 1
    you can see on the first answer says: **It really depends on your compiler, platform, and other details. However, I can describe one scenario where global variables are faster.** – TehMattGR Jul 06 '19 at 15:30
  • 3
    @TehMattGR: Lua is a *very different language* from C and C++. The nature of globals is *fundamentally different*. The stuff in that answer absolutely do not apply to what the OP is asking about. Consider the statement "a global variable is at a fixed offset"; that is *never true* in Lua. – Nicol Bolas Jul 06 '19 at 17:18
  • Note: A function is a value. So, the "calling" part of your example is outside the scope of the variable access timing question. – Tom Blodget Jul 07 '19 at 15:32

2 Answers2

4

In Lua, global variables are stored in a table called _G. Adding a key to a large table might occasionally be slow due to the possibility of having to resize the table. I don't know the threshold for when this slowdown becomes noticeable. As far as I know, accessing a key should be fast regardless of the table's size.

luther
  • 5,195
  • 1
  • 14
  • 24
4

Pretty much everything that stores data in Lua is a table of some form (local variables being the notable exception). This includes globals. So global accesses are table accesses, which are implemented as hash tables.

Access to a hash entry is amortized O(1), and therefore does not vary based on the number of entries in the table. Now, "amortized O(1)" does allow for some non-constant variance, but that will not be based on the size of the table so much as the way the hashes for the keys collide. Obviously, larger tables mean that more collisions are possible, but larger tables also use more hash entries, thus lowering the chances of collision. So the two generally cancel out.

Basically, you shouldn't care. Access to a global will not be the principle performance issue you will face in any real program.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982