Skip to content

Commit 0b34385

Browse files
committed
initial commit of library, tests
0 parents  commit 0b34385

10 files changed

+642
-0
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
node_modules
2+
deePool.js

.npmignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.gitignore
2+
node_modules

README.md

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
# deePool
2+
3+
A highly-efficient simple (no frills) object pool.
4+
5+
## Explanation
6+
7+
**deePool** (aka "deep-pool") is an object pool with efficiency (speed, low memory, little-to-no GC) as its primary design goal.
8+
9+
As such, there are no configuration options to tweak behavior. It does one thing, and one thing well. If you want to re-configure the behavior, modify the code. :)
10+
11+
Also, this library doesn't really try to do much in the way of graceful handling of errors or mistakes, as that stuff just slows it down. You should be careful in how you use *deePool*.
12+
13+
## Environment Support
14+
15+
This library requires ES6+ support. If you need to use it in ES<=5, transpile it with Babel yourself.
16+
17+
## Library API
18+
19+
There's only one method on the API:
20+
21+
```js
22+
deePool.create( objectFactory )
23+
```
24+
25+
* `create(..)`: produces a new pool instance. You can create as many separate pools as you need.
26+
27+
`objectFactory` must be a function that produces a single new empty object (or array, etc) that you want available in the pool. Examples:
28+
29+
```js
30+
var myArrays = deePool.create( function makeArray(){
31+
return [
32+
[ "foo", "bar", "baz" ],
33+
[ 1, 2, 3 ]
34+
];
35+
} );
36+
37+
var myWidgets = deePool.create( function makeWidgets(){
38+
return new SomeCoolWidget(1,2,3);
39+
} );
40+
```
41+
42+
### Pool API
43+
44+
Each pool has four simple methods on its API:
45+
46+
```js
47+
pool.use()
48+
49+
pool.recycle( obj )
50+
51+
pool.grow( additionalSize )
52+
53+
pool.size()
54+
```
55+
56+
* `pool.use()`: retrieves an available object instance from the pool. Example:
57+
58+
```js
59+
var arr = myArrays.use();
60+
```
61+
62+
**Note:** If the pool doesn't have any free instances, it will automatically grow (double in size, or set to `5` if currently empty) and then return one of the new instances.
63+
64+
* `pool.recycle(..)`: inserts an object instance back into the pool. Example:
65+
66+
```js
67+
myArrays.recycle( arr );
68+
```
69+
70+
**Tips:**
71+
- Don't forget to `recycle(..)` object instances after you're done using them. They are not automatically recycled, and your pool will run out of available instances, and thus keep growing unboundedly if you don't recycle.
72+
- Don't `recycle(..)` an object instance until you're fully done with it. As objects are held by reference in JS, if you hold onto a reference and modify an already recycled object, you will cause difficult to track down bugs in your application! To avoid this pitfall, unset your reference(s) to a pooled object immediately after `recycle(..)`.
73+
- Don't `recycle(..)` objects that weren't created for the pool and extracted by a previous `use()`.
74+
- Don't `recycle(..)` an object more than once. This will end up creating multiple references in the pool to the same object, which will cause difficult to track down bugs in your application! To avoid this pitfall, unset your reference(s) to a pooled object immediately after `recycle(..)`.
75+
- Don't create references between object instances in the pool, or you will cause difficult to track down bugs in your application!
76+
- If you need to "condition" or "reset" an object instance for its later reuse, do so before passing it into `recycle(..)`. If a pooled object holds references to other objects, and you want that memory freed up, make sure to unset those references.
77+
78+
**Note:** If you insert an object instance into a pool that has no empty slots (this is always a mistake, but is not disallowed!), the result will be that the pool grows in size by 1.
79+
80+
* `pool.grow(..)`: A number passed will specify how many instances to add to the pool (created by `objectFactory()` as specified in the [`deePool.create(..)` call](#Library_API)). If no number is passed, the default is the current size of the pool (effectively doubling it in size). Examples:
81+
82+
```js
83+
var myPool = deePool.create(makeArray);
84+
85+
var arr = myPool.use(); // pool size now `5`
86+
87+
myPool.grow( 3 ); // pool size now `8`
88+
myPool.grow(); // pool size now `16`
89+
```
90+
91+
**Tips:**
92+
- A new pool starts out empty (size: `0`). Always call `grow(..)` with a valid positive (non-zero) number to initialize the pool before using it. Otherwise, the call will have no effect; on an empty pool, this will confusingly leave the pool empty.
93+
- An appropriate initial size for the pool will depend on the tasks you are performing; essentially, how many objects will you need to use concurrently?
94+
95+
You should profile for this with your use-case(s) to determine what the most likely maximum pool size is. You'll want a pool size that's big enough so it doesn't have to grow very often, but not so big that it wastes memory.
96+
- Don't grow the pool manually unless you are really sure you know what you're doing. It's better to set the pool size initially and let it grow automatically (via `use()`) only as it needs to.
97+
98+
* `pool.size()`: Returns the number of overall slots in the pool (both used and unused). Example:
99+
100+
```js
101+
var myPool = deePool.create(makeArray);
102+
103+
myPool.size(); // 0
104+
105+
myPool.grow(5);
106+
myPool.grow(10);
107+
myPool.grow(5);
108+
109+
myPool.size(); // 20
110+
```
111+
112+
## Builds
113+
114+
The core library file can be built (minified) with an included utility:
115+
116+
```
117+
./build-core.js
118+
```
119+
120+
However, the recommended way to invoke this utility is via npm:
121+
122+
```
123+
npm run-script build-core
124+
```
125+
126+
## Tests
127+
128+
To run the tests, you must first [build the core library](#Builds).
129+
130+
With `npm`, run:
131+
132+
```
133+
npm test
134+
```
135+
136+
Or, manually:
137+
138+
```
139+
node node-tests.js
140+
```
141+
142+
## License
143+
144+
The code and all the documentation are released under the MIT license.
145+
146+
http://getify.mit-license.org/

build-core.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env node
2+
3+
var fs = require("fs"),
4+
path = require("path"),
5+
// ugly = require("uglify-js"),
6+
7+
result
8+
;
9+
10+
console.log("*** Building Core ***");
11+
console.log("Minifying to deePool.js.");
12+
13+
try {
14+
// result = ugly.minify(path.join(__dirname,"lib","deePool.src.js"),{
15+
// mangle: {
16+
// keep_fnames: true
17+
// },
18+
// compress: {
19+
// keep_fnames: true
20+
// },
21+
// output: {
22+
// comments: /^!/
23+
// }
24+
// });
25+
26+
27+
// NOTE: since uglify doesn't yet support ES6, no minifying happening,
28+
// just pass through copying. :(
29+
fs.writeFileSync(
30+
path.join(__dirname,"deePool.js"),
31+
32+
fs.readFileSync(path.join(__dirname,"lib","deePool.src.js")),
33+
34+
// result.code + "\n",
35+
{ encoding: "utf8" }
36+
);
37+
38+
console.log("Complete.");
39+
}
40+
catch (err) {
41+
console.error(err);
42+
process.exit(1);
43+
}

lib/deePool.src.js

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
(function UMD(name,context,definition){
2+
if (typeof define === "function" && define.amd) { define(definition); }
3+
else if (typeof module !== "undefined" && module.exports) { module.exports = definition(); }
4+
else { context[name] = definition(name,context); }
5+
})("deePool",this,function DEF(name,context){
6+
"use strict";
7+
8+
const EMPTY_SLOT = Object.freeze(Object.create(null));
9+
const NOTHING = EMPTY_SLOT;
10+
11+
return { create };
12+
13+
14+
// ******************************
15+
16+
// create a new pool
17+
function create(objectFactory = ()=>({})) {
18+
var objPool = [];
19+
var nextFreeSlot = null; // pool location to look for a free object to use
20+
var nextOpenSlot = null; // pool location to insert next recycled object
21+
22+
return {
23+
use,
24+
recycle,
25+
grow,
26+
size,
27+
};
28+
29+
30+
// ******************************
31+
32+
function use() {
33+
var objToUse = NOTHING;
34+
35+
// know where the next free object in the pool is?
36+
if (nextFreeSlot != null) {
37+
objToUse = objPool[nextFreeSlot];
38+
objPool[nextFreeSlot] = EMPTY_SLOT;
39+
}
40+
// otherwise, go looking
41+
else {
42+
// search starts with position + 1 (so, 0)
43+
nextFreeSlot = -1;
44+
}
45+
46+
// look for the next free obj
47+
for (
48+
var count = 0, i = nextFreeSlot + 1;
49+
(count < objPool.length) && (i < objPool.length);
50+
i = (i + 1) % objPool.length, count++
51+
) {
52+
// found free obj?
53+
if (objPool[i] !== EMPTY_SLOT) {
54+
// still need to free an obj?
55+
if (objToUse === NOTHING) {
56+
objToUse = objPool[i];
57+
objPool[i] = EMPTY_SLOT;
58+
}
59+
// this slot's obj can be used next time
60+
else {
61+
nextFreeSlot = i;
62+
return objToUse;
63+
}
64+
}
65+
}
66+
67+
// no other free objs left
68+
nextFreeSlot = null;
69+
70+
// still haven't found a free obj to use?
71+
if (objToUse === NOTHING) {
72+
// double the pool size (or minimum 5 if empty)
73+
grow(objPool.length || 5);
74+
75+
objToUse = objPool[nextFreeSlot];
76+
objPool[nextFreeSlot] = EMPTY_SLOT;
77+
nextFreeSlot++;
78+
}
79+
80+
return objToUse;
81+
}
82+
83+
function recycle(obj) {
84+
// know where the next empty slot in the pool is?
85+
if (nextOpenSlot != null) {
86+
objPool[nextOpenSlot] = obj;
87+
obj = NOTHING;
88+
}
89+
// otherwise, go looking
90+
else {
91+
// search starts with position + 1 (so, 0)
92+
nextOpenSlot = -1;
93+
}
94+
95+
// look for the next empty slot
96+
for (
97+
var count = 0, i = nextOpenSlot + 1;
98+
(count < objPool.length) && (i < objPool.length);
99+
i = (i + 1) % objPool.length, count++
100+
) {
101+
// found empty slot?
102+
if (objPool[i] === EMPTY_SLOT) {
103+
// obj still needs to be reinserted?
104+
if (obj !== NOTHING) {
105+
objPool[i] = obj;
106+
obj = NOTHING;
107+
}
108+
// this empty slot can be used next time!
109+
else {
110+
nextOpenSlot = i;
111+
return;
112+
}
113+
}
114+
}
115+
116+
// no empty slots left
117+
nextOpenSlot = null;
118+
119+
// still haven't recycled obj?
120+
if (obj !== NOTHING) {
121+
// insert at the end (growing size of pool by 1)
122+
// NOTE: this is likely mis-use of the library
123+
objPool[objPool.length] = obj;
124+
}
125+
}
126+
127+
function grow(count = objPool.length) {
128+
nextFreeSlot = objPool.length;
129+
130+
for (var i = 0; i < count; i++) {
131+
// add new obj to pool
132+
objPool[objPool.length] = objectFactory();
133+
}
134+
135+
// look for an open slot
136+
nextOpenSlot = null;
137+
for (var i = 0; i < nextFreeSlot; i++) {
138+
// found an open slot?
139+
if (objPool[i] === EMPTY_SLOT) {
140+
nextOpenSlot = i;
141+
break;
142+
}
143+
}
144+
}
145+
146+
function size() {
147+
return objPool.length;
148+
}
149+
}
150+
151+
});

node-tests.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/usr/bin/env node
2+
3+
global.deePool = require("./lib/deePool.src.js");
4+
global.QUnit = require("qunitjs");
5+
6+
require("./qunit.config.js");
7+
require("./tests.js");
8+
9+
// temporary hack per: https://github.com/qunitjs/qunit/issues/1081
10+
QUnit.load();

package.json

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
{
2+
"name": "deepool",
3+
"version": "1.0.0",
4+
"description": "deePool: highly-efficient pool for objects",
5+
"main": "./lib/deePool.src.js",
6+
"scripts": {
7+
"test": "./node-tests.js",
8+
"build-core": "./build-core.js",
9+
"build": "npm run build-core",
10+
"prepublish": "npm run build-core"
11+
},
12+
"devDependencies": {
13+
"qunitjs": "~2.1.0",
14+
"uglify-js": "~2.7.5"
15+
},
16+
"keywords": [
17+
"object",
18+
"pool",
19+
"performance"
20+
],
21+
"author": "Kyle Simpson <[email protected]>",
22+
"license": "MIT"
23+
}

0 commit comments

Comments
 (0)