Search code examples
haxehaxeflixel

Correct way to instantiate a FlxPoint


(I'm using the dev branch of HaxeFlixel)

To create a new FlxPoint variable I can do one of three things...

var pt:FlxPoint = new FlxPoint();
var pt:FlxPoint = FlxPoint.weak();
var pt:FlxPoint = FlxPoint.get();

From reading the method comments, I've figured out there's some sort of pooling going on to presumably speed up creating FlxPoints. Under what circumstances should I use each of the three ways to create a new FlxPoint?

I have several functions that either accept FlxPoints as parameters, or return them. Should I copy what FlxPoint itself does, and use .weak() to create them, and .putWeak() to recycle points passed into functions?

To me it seems .get() is for long-lived variables (player start positions, points stored in an array for path finding, etc), and .weak() is for temporary ones (intermediate values calculated within a function). Is this right?


Solution

  • FlxPoint provides a pooling mechanism that is supposed to help reduce garbage collection.

    FlxPoint.get() attempts to retrieve an unused point from the pool. If there isn't one, it's effectively the same as new FlxPoint(). Either one can be recycled by being put() back into the pool.

    weak() is more about being used for library calls than longevity (though that does often mean it's short-lived) - here is its documentation:

    Recycle or create a new FlxPoint which will automatically be released to the pool when passed into a flixel function.

    This means you don't need to worry about keeping a reference to the pivot point and recycling it in this example, since rotate() calls putWeak() on it for you:

    point.rotate(FlxPoint.weak(0, 0), 45);