Returns an object pool identified with the given name. If no pool with the given name exists, it will create a
new pool.
Parameters:
Name |
Type |
Description |
options |
object
|
Properties
Name |
Type |
Argument |
Default |
Description |
name |
string
|
|
|
The name that identifies this pool |
ctor |
function
|
<optional>
|
|
A constructor, that, when called with the new keyword, returns a new object |
createObject |
function
|
<optional>
|
|
A function that returns a new object |
preAllocate |
number
|
<optional>
|
0
|
The number of objects to pre-allocate |
resetObject |
function
|
<optional>
|
|
A function that will turn a used, 'dirty' object into a clean state |
|
- Version:
-
- Source:
-
Returns:
An object pool
-
Type
-
Pool
Examples
// create a pool for a given `Vector3` class
var vec3Pool = fastPool({
name: 'vec3',
ctor: Vector3,
preAllocate: 20
});
// get a Vector3 instance from the pool
var vec3 = vec3Pool.transfer();
// when it's no longer needed, return it to the pool
vec3Pool.takeBack(vec3);
// Extending the example above, but making sure the Vector3 instances are in a clean
// state whenever one is transferred from the pool. The resetObject function is called
// during `takeBack`, before the object is put back into the pool.
var vec3Pool = fastPool({
name: 'vec3',
ctor: Vector3,
preAllocate: 20,
resetObject: function (vec3) {
vec3.set(0, 0, 0);
}
});
// get a Vector3 instance from the pool
var vec3 = vec3Pool.transfer();
// do work, and then back to the pool
vec3.x = 5;
vec3Pool.takeBack(vec3); // before the object is put back into the pool, it gets reset.
// Create pool of Float32Arrays with a given size. Passing only the constructor does not
// work, as it needs an argument, so using the `createObject` property here instead of `ctor`.
var matrix16Pool = fastPool({
name: 'matrix4',
preAllocate: 100,
createObject: function () {
return new Float32Array(16);
}
});
// Create a pool of complex objects with unknown quantity for runtime, so keep the
// pre-allocation low.
var tieFighterPool = fastPool({
name: 'TieFighter',
preAllocate: 5,
createObject: function () {
var tieFighter = new Fighter({
type: 'TieFighter',
AIStrength: 3
});
tieFighter.setTarget(player);
return tieFighter;
},
resetObject: function (tieFighter) {
tieFighter.clearTarget();
tieFighter.resetPosition();
}
});