When I pressed the 'btn' memory rose up from 80M to 240M. And I pressed the 'btn2' to remove the object(self.sprite) include many lua table, but the memory didn't go down.
What wrong with this code? Or it is a lua bug?
I used cocos2dx-3.8.1/xcode7/ios simulator.
local MainScene = class("MainScene", cc.load("mvc").ViewBase)
function MainScene:onCreate()
local btn = ccui.Button:create("res/Button_Normal.png","res/Button_Press.png","res/Button_Disable.png")
btn:setScale9Enabled(true)
btn:setContentSize(cc.size(70,70))
btn:setPosition(100,100)
btn:setTitleColor(cc.c3b(0,0,0))
btn:setTitleFontSize(30)
btn:setTitleText("Add")
btn:addTouchEventListener(function(ref,typ)
if typ == ccui.TouchEventType.ended then
self.sprite = cc.Sprite:create("res/Button_Normal.png")
for i=1,1000000 do
self.sprite["s_"..i] = {"abc",123}
end
self.sprite:setPosition(100, 200)
self:addChild(self.sprite)
end
end)
self:addChild(btn)
local btn2 = ccui.Button:create("res/Button_Normal.png","res/Button_Press.png","res/Button_Disable.png")
btn2:setScale9Enabled(true)
btn2:setContentSize(cc.size(70,70))
btn2:setPosition(200,100)
btn2:setTitleColor(cc.c3b(0,0,0))
btn2:setTitleFontSize(30)
btn2:setTitleText("remove")
btn2:addTouchEventListener(function(ref,typ)
if typ == ccui.TouchEventType.ended then
if self.sprite then
self.sprite:removeFromParent(true)
self.sprite = nil
end
end
end)
self:addChild(btn2)
end
return MainScene
It's probably not a memory leak. You can use Lua garbage collection methods to see how much memory Lua allocates to those structures. For example, try the following:
collectgarbage("count") -- #1 returns something like 2574.62890625 (in Kb)
-- allocate and release memory
collectgarbage() -- collect memory
collectgarbage()
collectgarbage("count") -- #2 check the amount of memory
You should see about the same amount of memory used in 1 and 2 (assuming everything that was allocated was released as it doesn't have anything holding a reference), but in general you should not expect the memory reported by the operating system to go down to the original amount because of the fragmentation. You should expect Lua to continue reusing the memory it released, so if you allocate the same structures again, the total amount of memory will stay approximately the same.
I doubt there is a memory leak in Lua unless you can demonstrate it on a much simpler script that doesn't involve cocos2dx API.