Created
April 29, 2023 09:22
-
-
Save epreston/ca956d15485092ca59ddc36edbf465d8 to your computer and use it in GitHub Desktop.
add object pool support to a prototype - avoid small object allocation with reuse - alloc, get, release
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
const isFn = (a) => typeof a === 'function'; | |
export function addObjectPool(objtype, resetFunction, maxSize = Number.MAX_SAFE_INTEGER) { | |
const pool = []; | |
function newObject() { | |
return new objtype(); | |
} | |
if (isFn(resetFunction)) { | |
objtype.prototype.onPoolReset = resetFunction; | |
} | |
objtype.prototype.release = function () { | |
objtype.release(this); | |
return this; | |
}; | |
objtype.alloc = (count) => { | |
if (!(count <= 0)) for (; count--; ) objtype.release(newObject()); | |
}; | |
objtype.get = () => { | |
const object = pool.pop() || newObject(); | |
object.onPoolReset && object.onPoolReset(object); | |
return object; | |
}; | |
objtype.release = (...args) => { | |
let index = args.length; | |
for (; index--; ) pool.length < maxSize && pool.push(args[index]); | |
}; | |
return objtype; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
Given a class that has some way to reset its values to default, or this can be done in a reset funciton, we call this Functional Mixin to add object pool support. In this case, the example object already has a
resetTo
method that can do this.