memory-pool
Introduction
This library implements a very fast memory pool. It can be used in game engines for the purpose of storing multiple objects of the same type.
Here are benchmark results collected on Google Chrome 50.0.2661.102 m (64-bit) running on Windows 10 and Intel i7-3930K@3.2GHz. Source code of the benchmark is available here:
- benchmark/001-comparison/index.html
- benchmark/002-average-time/index.html
- benchmark/003-comparison-render-loop/index.html
Note on the last benchmark the memory graph. First half presents graph of memory usage for MemoryLoop while second contains 'new' keyword.
Also, the cost of Garbage Collection is now more visible than in any other of the benchmarks. While 'new' keyword performance dropped twice, Memory Pool retained most of it's speed - the difference is just around 2ms which might be caused by external system factors.
Installation
npm install memory-pool
Usage - web browser
Before you start using this library simply include the node_modules/memory-pool/dist/memory-pool.js
file on your website.
It's recommended to include this file in your assets pipeline and concatenate it with the rest of your javascript files.
Usage - Node.js
To include the memory pool within Node.js app simply load the module.
var MemoryPool = ;
Creating memory pool
The following example creates a homogeneous memory pool. objectFactory
function creates
a new EMPTY instance of the object to store in the memory. Memory gets filled with
the specified amount of elements of the same type. In this example it's 1024 objects of
a type foo
. Library adds a custom field to the class '__memoryAddress__' which is used
for performance reasons. Make sure your objects are not overwriting that field or MemoryPool will break.
{ this { console; };} { return ;} var size = 1024;var memoryPool = size objectFactory;
Allocating and de-allocating objects
This example presents how to allocate and de-allocate objects using the library.
{ this { console; };} { return ;} var size = 1024;var memoryPool = size objectFactory; // Allocating new objectvar bar = memoryPool; // This returns the object of a type 'foo' // Doing something with your objectbar; // free the object and return it to the poolmemoryPool;
Dynamic memory pool size expansion
This memory pool supports dynamic resizing. In case you allocate more objects than the number predicted in the constructor, the library will automatically expand the size by default amount of 256 elements. You can override that value using third constructor argument.
var size = 1;var growBy = 2;var memoryPool = size objectFactory growBy; // Allocate first object. Size won't change.var first = memoryPool; // Allocate second object. Memory pool will expand by 2.var second = memoryPool; // Allocate third object. Memory pool size won't change - now it can accommodate 3 objects.var third = memoryPool; // Remember to ALWAYS release the objects// otherwise you'll end up with memory leaksmemoryPool;memoryPool;memoryPool;