(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 FlxPoint
s. Under what circumstances should I use each of the three ways to create a new FlxPoint
?
I have several functions that either accept FlxPoint
s 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?
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);
FlxPoint.get()
retrieves a FlxPoint from the pool and requires you to manually put()
it back when you are finished with it. Use this for long-lived variables. You might use get()
in a constructor and put()
in the destroy
method of a class that needs a point member variable.
FlxPoint.weak()
gives you a point that gets returned to the pool when put()
or putWeak()
is called on it. Like you say, using them for temporary or intermediate values is best. HaxeFlixel does this for methods that take FlxPoints, and you can follow that pattern in your own code too.
Instantiating a FlxPoint with new
creates one without pooling. The garbage collector takes care of it, provided you don't hang on to references to it. It's fine to do this for the odd point, and it's fine whenever performance or garbage collection pauses aren't a big concern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With