Oh, one more thing, about the memory usage, the up-values cost much more if you use the local vars in many functions in your add-on, Here is a little test :
Lua Code:
do
clear = function() collectgarbage() return collectgarbage("count") end
for i = 1, 10 do
_G["a"..i] = function() end
end
memStep0 = clear()
do
local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 = a1, a2, a3, a4, a5, a6, a7, a8, a9, a10
for i = 1, 100 do
_G["A"..i] = function()
a1() a2() a3() a4() a5() a6() a7() a8() a9() a10()
end
_G["A"..i]()
end
end
memStep1 = clear()
do
local addon = {}
addon._Addon = addon -- the addon itself
if not getmetatable(addon) then
setmetatable(addon, {
__index = function(self, key)
-- keep vars in the _G to the addon to reduce the access cost
local v = _G[key]
if v ~= nil then
rawset(self, key, v)
return rawget(self, key)
end
end,
__metatable = true,
})
end
setfenv(1, addon)
for i = 1, 100 do
_Addon["A"..i] = function()
a1() a2() a3() a4() a5() a6() a7() a8() a9() a10()
end
_Addon["A"..i]()
end
end
memStep2 = clear()
print("Cost for up-values", memStep1 - memStep0)
print("Cost for standalone environment", memStep2 - memStep1)
end
So, here is the result:
Cost for up-values 22.275390625
Cost for standalone environment 9.9453125
|