高效是指性能。如果必须快速访问类成员(例如在绘制UI时),为它们建立索引的最佳方法是什么?
我的理解是,基于表的类使用更少的内存,并且创建实例的速度更快,而基于闭包的类具有更快的函数调用,并且让您拥有私有字段,这些私有字段由于作为upvalue存储而被快速索引。对于以下示例类,这种情况的最佳实现是什么?
-- Example of Table-based Class
local class = {}
class.x = 0
class.y = 0
class.w = 0
class.h = 0
-- Draw would be called for potentially dozens of instances many times per second
function class:Draw()
draw_rect(self.x, self.y, self.w, self.h)
end
-- Example of Closure-based class
local function class(_x, _y, _w, _h)
-- the new instance
local self = {
-- public fields
visible = false
}
-- private fields are locals
local x, y, w, h = _x, _y, _w, _h
function self.SetPos(_x, _y)
x = _x
y = _y
end
function self.GetPos()
return x, y
end
function self.GetVisible()
return self.visible
end
-- return the instance
return self
end
local obj = class(10, 20, 40, 80)
print(obj.GetPos()) --> 10, 20
obj.SetPos(50, 100)
print(obj.GetPos()) --> 50, 100
obj.x = 21
obj.y = 42
print(obj.GetPos()) --> 50, 100 (unchanged, private)
obj.visible = true
print(obj.GetVisible()) -- true (public)