Whenever I use iterators in update loops I have memory leak issues. For example, here:
class Manager extends FlxState {
public var array: Array<Int>;
override public function create():Void {
array = new Array();
}
public override function update() {
super.update();
/////////////////////////////////////////////////////
//
// ISSUE IS HERE
// If for(item in array) line is present there's a memory
// issue.
//
/////////////////////////////////////////////////////
for(item in array) var noop:Int = 0 /* Do nothing */;
}
}
When this is run I will get a constant memory increase that goes on forever. This is how it looks in HaxeFlixel's debugger:
However, If I iterate using a simple loop like this:
for(i in (0...array.length)) var noop:Int = 0;
It will be fine:
Why is this happening and what am I doing wrong?
Thanks.
It was happening because the iterator is allocating memory for the iterator.
After a while the memory is collected by the garbage collector.
I did a stress test using 1000 arrays
class Manager extends FlxState {
public var arrays: Array<Array<Int>>;
override public function create():Void {
arrays = new Array();
for (i in (0...1000)) arrays.push(new Array());
}
public override function update() {
super.update();
for (array in arrays)
for (i in array)
var noop:Int = 0;
}
}
And eventually memory was collected: