访问 Lua 中的元表时的时间复杂度

访问 ins.base 的时间复杂度是 O(1)。

点赞
用户646619
用户646619

你可以从官方 Lua 实现中期望 O(1) 的时间复杂度。

__index 的代码与 Lua 手册中给出的代码大致等价:

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))     -- 调用处理器
  else return h[key]           -- 或在其上重复操作
  end
end

__index 本身没有循环,而且由于 Lua 表是由哈希表支持的,所以表查找通常是一个常量时间操作。

2014-04-24 14:15:24