Search code examples
haxehaxeflixel

Haxe memory issue with iterators in FlxState.update function


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:

memorynornormal

However, If I iterate using a simple loop like this:

for(i in (0...array.length)) var noop:Int = 0;

It will be fine:

memorynormal

Why is this happening and what am I doing wrong?

Thanks.


Solution

  • 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:

    memorycollected