Created
March 29, 2019 19:20
-
-
Save sketchpunk/62a87932199318d7491b0d4062b34759 to your computer and use it in GitHub Desktop.
ObjectPool - Very bare bones for maximum performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* NOTES | |
When i create 5 Float32Arrays at 10 million iterations, It takes about 3 seconds to complete. | |
But if create a Pool of 5 Float arrays and use Get/Rtn at the same interactions is only 0.17s. | |
So by using ObjectPool, using Float32Arrays for Vector3 data is just as fast as an Object Vector | |
but uses up less memory and affects garbage collection much less. | |
let pool = new ObjectPool( THREE.Vector3, 10, 5 ); | |
let a = pool.get(), | |
b = pool.get(); | |
pool.rtn( a ).rtn( b ); | |
*/ | |
class ObjectPool{ | |
constructor( obj, cnt=10, rCnt=5 ){ | |
this.maxIdx = cnt-1; | |
this.curIdx = this.maxIdx; | |
this.obj = obj; | |
this.pool = new Array( cnt ); | |
this.resizeCnt = rCnt; | |
// Initialize the pool; | |
for( let i=0; i < cnt; i++ ) this.pool[ i ] = new obj(); | |
} | |
// Get an Item, Create more if not available | |
// NOTES: | |
// Using index instead of push / pop, shaves off an extra 0.07s on 10 million calls. | |
get(){ | |
if( this.curIdx == -1 ){ | |
console.log("POOLRESIZE -", this.obj.name ); | |
let p = this.pool, t = this.obj; | |
p.length += this.resizeCnt; | |
for( let i=0; i < this.resizeCnt; i ++ ) p[i] = new t(); | |
this.maxIdx = p.length - 1; | |
this.curIdx = this.resizeCnt-1; | |
} | |
return this.pool[ this.curIdx-- ]; | |
} | |
// Return Single Item back to the Pool | |
// NOTES: | |
// Tried to use a Loop and Arguments array but that really | |
// killed performance. Also did an instanceOf check before | |
// allowing a return which eats up time. So sticking to | |
// this bare bones rtn function gives me 10 million calls at 0.18 seconds. | |
// with instanceOf, 2 seconds, with loop 7.6 seconds. | |
rtn( o ){ this.pool[ ++this.curIdx ] = o; return this; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment