pool

Efficient macro-powered object pooling library.


Keywords
allocate, management, memory, pool, pooling, recycle, reuse
License
MIT
Install
haxelib install pool 0.1.1

Documentation


  • Efficient object pooling with zero overhead.
  • No reflection, 100% macro-generated code.
  • Only static field accesses are generated, no slow dynamic lookups.
  • Intuitive usage, each object needs only a constructor and nothing else.

Installation

$ haxelib install pool

Usage

Pooled objects

Types which are to be pooled, should implement the Poolable interface.

class Vector2 implements Poolable {
    var x: Float;
    var y: Float;

    public function new(x: Float, y: Float) {
        this.x = x;
        this.y = y;
        // anything else
    }
}

It might be a good idea to hide the constructor, and make sure that it is only accessible by the Pool class. This ensure that objects are only created through the pooling system.

class User implements Poolable {
    var username: String;

    @:allow(pool.Pool)
    private function new(username: String) {
        this.username = username;
    }
}

Static pools

Then it is necessary to define an empty class, where the pooling code will be generated.

The following example will create a pool which will support all the Poolable objects under the my.objects package.

@:build(pool.macro.PoolBuilder.build("my.objects"))
class GlobalPool extends Pool { }

This pool class will be static, because the second argument generateStatic to the builder is optional and defaults to true.

// Retrieve objects from the pool using the type's constructor parameters.
var v: Vector2 = GlobalPool.getVector2(5, 10);

// Discard objects by putting them back in the pool so that they may be reused.
// Objects put back in the pool should not be used again.
GlobalPool.putVector2(v);

Instance pools

As mentioned above, passing false as the second arguments to PoolBuilder.build() will generate a pool class with non-static fields.

@:build(pool.macro.PoolBuilder.build("my.objects", false))
class LocalPool extends Pool { }
var myPool = new LocalPool();

var u: User = myPool.getUser("anon");

myPool.putUser(u);

This might be useful for example in the case of multi-threading, where a common static pool would be prone to race conditions.

Object initialization

The constructor of each pooled type is copied, and is automatically used whenever an object is recycled.

Therefore an object's initialization steps need only be implemented once, in the constructor.

class Apple implements Poolable {

    public function new() {
        trace('an Apple object was either created or recycled');
    }
}