Skip to content

Instantly share code, notes, and snippets.

@azrafe7
Created June 23, 2014 19:53
Show Gist options
  • Save azrafe7/8cc8a3a416b022c6eb98 to your computer and use it in GitHub Desktop.
Save azrafe7/8cc8a3a416b022c6eb98 to your computer and use it in GitHub Desktop.
Modified FlxPool class
package flixel.util;
import flixel.util.FlxDestroyUtil.IFlxDestroyable;
/**
* A generic container that facilitates pooling and recycling of objects.
* WARNING: Pooled objects must have parameterless constructors: function new()
*/
@:generic
class FlxPool<T:IFlxDestroyable>
{
private var _pool:Array<T>;
private var _class:Class<T>;
private var _length:Int = 0;
public var length(get, never):Int;
public function new(classObj:Class<T>)
{
_pool = [];
_class = classObj;
}
public inline function get():T
{
return (_length > 0) ? _pool[--_length] : Type.createInstance(_class, []);
}
public function put(obj:T):Void
{
// we don't want to have the same object in pool twice
if (obj != null)
{
var idx = _length;
while (--idx >= 0) if (_pool[idx] == obj) break;
if (idx >= 0) return;
obj.destroy();
_pool[_length++] = obj;
}
}
public inline function putUnsafe(obj:T):Void
{
if (obj != null)
{
obj.destroy();
_pool[_length++] = obj;
}
}
public function preAllocate(numObjects:Int):Void
{
for (i in 0...numObjects)
{
_pool[_length + i] = Type.createInstance(_class, []);
_length++;
}
}
public function clear():Array<T>
{
var oldPool = _pool;
_pool = [];
_length = 0;
return oldPool;
}
private inline function get_length():Int
{
return _length;
}
}
interface IFlxPooled extends IFlxDestroyable
{
public function put():Void;
private var _inPool:Bool;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment