I’ve run into memory creep issues. I have a grid which is made up of lots of class instances. I wanted to be able to turn on touch listeners for all my grid squares easily and created some functions to do that. And I didn’t want to have to keep track of whether I had added a listener in order to avoid multiple event listeners, so I thought I would start every addition of the event listener with a removal. 99 times out of 100 the removal is unnecessary, but I thought that this should make sure I don’t ever have multiple listeners attached to the same object.
But I’m flicking these squares on and off very rapidly and my memory is creeping up. And the memory creep seems to be a simple function of how many times I flick the touch event listeners off and on. See the code below for a simplified example of what I’m doing. If you increase the variable “numberOfCycles” you will see memory usage go up and up. And forcing garbage removal doesn’t seem to make any difference.
What am I doing wrong? Aside from wasteful inelegant code? Thanks for any help!
Matt
(apologies if this comes out badly formatted, it seems to be an iPad issue)
[lua]
local class = require(“30log”)
local jelly = class()
function jelly:init()
self.circle = display.newCircle( math.random(700), math.random(1000), math.random(10,20) )
end
function jelly:on()
self.circle:removeEventListener(“touch”, self)
self.circle:addEventListener(“touch”, self)
end
local jellies = {}
for i = 1, 500 do
jellies[#jellies+1] = jelly()
end
print( “Memory after creating 500 instances”, collectgarbage(“count”) )
local function turnAllOn()
for i = 1, #jellies do
jellies[i]:on()
end
end
local numberOfCycles = 100
for i = 1, numberOfCycles do
turnAllOn()
end
print( collectgarbage(“count”) )
[/lua]