楼主你好,对于Lua配置表优化笔记我有个问题不大理解,文中给的优化方案在访问时元方法里面实际上还是进行了一次key-value的哈希吧,好像还是牺牲了时间来换空间,并不是文中说的优化了访问时间,我测了下在访问时间上应该是比优化前更耗时的,以下是我测试的代码和结果 local loopTimes = 100000 local _key2index = { id = 1, name = 2, number = 3 } local _o = { __index = function(data, key) local index = _key2index[key] if index == nil then return nil end return data[index] end, __newindex = function(data, key, value) error("Can't modify a readonly table!") end } local _M = { [1] = setmetatable({1,"test1",100}, _o), [2] = setmetatable({2,"test2",200}, _o) } local _X = { [1] = { id = 1,name = "test1",number = 100 }, [2] = { id = 2,name = "test2",number = 200 } } local a print(os.clock()) for i = 1,loopTimes do a = _M[1].id end print(os.clock()) for i = 1,loopTimes do a = _M[1].id end print(os.clock()) for i = 1,loopTimes do a = _X[1].id end print(os.clock())
点赞 3

相关推荐

Java抽象带篮子:难蚌,点进图片上面就是我的大头😆
点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客网
牛客企业服务