Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 563
Piku Avatar asked Jan 23 '16 21:01

Piku


2 Answers

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);
like image 107
Gama11 Avatar answered Sep 23 '22 02:09

Gama11


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.

like image 34
Sam Twidale Avatar answered Sep 20 '22 02:09

Sam Twidale