Pooling
When building Games, you often use objects that are quite expensive to create and clean up (GC). These costs can be high enough to affect the game's performance. Nez offers the ObjectPool and ListPool to solve this.
An Object pool is a container of objects that contains a list of objects that are ready to be used. Once an object is taken out of the pool, it is no longer available in the pool until it is put back in.
#
Pool#
ExampleAs an example to show how you can use a Pool
, I created a simple tree that retrieves its nodes from a Pool
.
As you can see in the code above, SomeNode
inherits IPoolable
.
IPoolable is an interface used by the pool to reset the object. It is not mandatory to implement this, but it can be useful.
InstanceCount
is used to find out how many instances have been created.
The tree uses the Pool
in the Clear
and void Add(ref SomeNode node, int value)
methods.
After creating the tree, 5 nodes were instantiated.
With the Clear
method we put them back into the pool.
Then we create a new tree.
no new nodes were created because they where reused from the pool.
#
ExtraPool
also has a few features that were not present in the example.
Pool<>.ClearCache
#
Removes all pooled items.
Pool<>.WarmCache
#
Add instances to the pool.
Pool<>.TrimCache
#
Removes items from the pool until the pool is at the desired trim size.
#
ListPoolListPool
works the same as Pool
, except that the list is automatically emptied by the Free
method.