Last active
October 28, 2020 06:10
-
-
Save YonatanKra/c3899fcf0f0556a7a4ae0d73589df9f4 to your computer and use it in GitHub Desktop.
Non-performant object pool
This file contains 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
class ObjectPool { | |
constructor(objectConstructor, objectReseter, initialSize = 5000) { | |
this.objectConstructor = objectConstructor; | |
this.objectReseter = objectReseter; | |
this._pool = []; | |
for (let i = 0; i < initialSize; i++) { | |
this._addObjectToPool(); | |
} | |
} | |
_addObjectToPool() { | |
const newObj = { | |
alive: false, | |
data: this.objectConstructor() | |
}; | |
this._pool.push(newObj); | |
} | |
_allocate(object) { | |
object.alive = true; | |
return object; | |
} | |
getNew() { | |
for (let i = 0; i < this._pool.length; i++) { | |
if (this._pool[i].alive === false) { | |
return this._allocate(this._pool[i]); | |
} | |
} | |
return this._addObjectToPool(); | |
} | |
release(object) { | |
object.alive = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment