Search code examples
lualua-tablemetatable

time complexity of metatable in Lua when accessing


local cls = {base = "base"}
local ins = {}
cls.__index = cls
setmetatable(ins, cls)

What is the time complexity of accesssing ins.base?


Solution

  • You can expect O(1) time complexity from the official Lua implementation.

    The code for __index is roughly equivalent to this Lua code, taken from the manual:

     function gettable_event (table, key)
       local h
       if type(table) == "table" then
         local v = rawget(table, key)
         if v ~= nil then return v end
         h = metatable(table).__index
         if h == nil then return nil end
       else
         h = metatable(table).__index
         if h == nil then
           error(···)
         end
       end
       if type(h) == "function" then
         return (h(table, key))     -- call the handler
       else return h[key]           -- or repeat operation on it
       end
     end
    

    The __index lookup itself has no loops, and since Lua tables are backed by hash tables, table lookups are usually a constant-time operation.