Skip to content

Instantly share code, notes, and snippets.

@katsaii
Last active September 3, 2022 22:34
Show Gist options
  • Save katsaii/10b866be9057ee0a32410b2735720b46 to your computer and use it in GitHub Desktop.
Save katsaii/10b866be9057ee0a32410b2735720b46 to your computer and use it in GitHub Desktop.
A simple "ds_map" pooling example using probability to avoid constantly polling whether references are still alive. Technically unbound space complexity, but it is extremely unlikely to occur unless you're creating many new instances per frame without letting the garbage collector catch up.
/// @ignore
function __pool() {
static pool = [];
return pool;
}
function pool_get(container) {
var pool = __pool();
var poolMax = array_length(pool) - 1;
if (poolMax >= 0) {
repeat (3) { // the number of retries until a new resource is created
var i = irandom(poolMax);
var weakRef = pool[i];
if (weak_ref_alive(weakRef)) {
continue;
}
var newWeakRef = weak_ref_create(container);
var ds = weakRef.ds;
newWeakRef.ds = ds;
ds_map_clear(ds);
pool[@ i] = newWeakRef;
return newWeakRef;
}
}
var weakRef = weak_ref_create(container);
weakRef.ds = ds_map_create();
array_push(pool, weakRef);
return weakRef;
}
function pool_collect() {
var pool = __pool();
var poolSize = array_length(pool);
for (var i = poolSize - 1; i >= 0; i -= 1) {
var weakRef = pool[i];
if (weak_ref_alive(weakRef)) {
continue;
}
ds_map_destroy(weakRef.ds);
array_delete(pool, i, 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment