设置元表: 引用 VS 内联的优势?

我在想,当您想要为多个表使用相同的元表时,通过引用传递元表会比在 setmetatable() 中声明内联更有意义吗?

我的目标是为了节省内存,但只有在真正有显着差异时才这样做。

我谈论的是这个:

-- 通过引用传递元表:
JSON1 = {
    metaTable = {
        __index = function (t, k)
            -- ...
        end;
        __call = function()
            -- ...
        end
    };
    parse = function(filePath)
        local fakeParsedJson = {}
        setmetatable(fakeParsedJson, JSON1.metaTable) -- 此处
        return fakeParsedJson(filePath)
    end;
}

VS

-- 内联传递表格:
JSON2 = {
    parse = function(filePath)
        local fakeParsedJson = {}
        setmetatable(fakeParsedJson, { -- 此处:
            __index = function (t, k)
                -- ...
            end;
            __call = function()
                -- ...
            end
        })
        return fakeParsedJson(filePath)
    end;
}

我试图找出内存使用情况是否有显着差异,但我能找到的唯一方法是比较 gcinfo:

local start1 = gcinfo()
local example2_1 = JSON2.parse('example2_1.json')
local example2_2 = JSON2.parse('example2_2.json')
local example2_3 = JSON2.parse('example2_3.json')
local example2_4 = JSON2.parse('example2_4.json')
local example2_5 = JSON2.parse('example2_5.json')
print(gcinfo()-start1) -- 打印 1

local start2 = gcinfo()
local example1_1 = JSON1.parse('example1_1.json')
local example1_2 = JSON1.parse('example1_2.json')
local example1_3 = JSON1.parse('example1_3.json')
local example1_4 = JSON1.parse('example1_4.json')
local example1_5 = JSON1.parse('example1_5.json')
print(gcinfo()-start2) -- 打印 1

这是我的 fiddle:https://repl.it/HfwS/34

看起来似乎没有什么区别。但是我不知道在幕后实际发生了什么。

当您调用 setmetatable(myTable,myMetaTable) 时,它会在 myTable 中写入 myMetaTable 的完整副本,还是仅存储一个简单的引用?因为如果它只存储一个引用,那么让所有我的表格指向同一个元表将非常有意义。

点赞