Cocos2dx-lua cc.p优化技巧

local ccp_mt = {
    __index = function(t, k)
        if k == "x" then
            return t[1]
        elseif k == "y" then
            return t[2]
        else
            return rawget(t, k)
        end
    end,
    __newindex = function(t, k, v)
        if k == "x" then
            t[1] = v
        elseif k == "y" then
            t[2] = v
        else
            rawset(t, k, v)
        end
    end
}

function p(x,y)
    if nil == y then
         return setmetatable({ x.x, x.y }, ccp_mt)
    else
         return setmetatable({ x, y }, ccp_mt)
    end
end

-- for i=1,1024 do
--     _G[tostring(i)] = p(1,2)
-- end

print(collectgarbage("count"))

-- for i=1,1024 do
--     _G[tostring(i)] = nil
-- end


function p(_x,_y)
    if nil == _y then
         return { x = _x.x, y = _x.y }
    else
         return { x = _x, y = _y }
    end
end
collectgarbage("collect")

-- for i=1,1024 do
--     _G[tostring(i)] = p(1,2)
-- end

print(collectgarbage("count"))

多一个met表的空间让每个p更瘦了~

不考虑性能了吗

负优化,性能变慢,可读性变差