2014-04-24 19 views
2
local cls = {base = "base"} 
local ins = {} 
cls.__index = cls 
setmetatable(ins, cls) 

訪問ins.base的時間複雜度是多少?訪問時Lua中metatable的時間複雜度

+0

我相信第三行應該是cls .__ index = cls – mpeterv

+0

沒錯。我的錯誤@peterm – 1hunch1kill

+0

我認爲時間複雜度與'cls.base'相同。您只需添加多個哈希查找。在最好的O(1)中,哈希查找的時間複雜度最差的是O(n) – moteus

回答

3

您可以期望從官方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))  -- call the handler 
    else return h[key]   -- or repeat operation on it 
    end 
end 

__index查找本身沒有環路,並且由於Lua的表由哈希表的支持下,表查找通常是恆定時間的操作。