screeps-clockwork

WASM Object Cleanup

Clockwork objects often wrap Rust-backed WASM allocations. JavaScript garbage collection can eventually release those allocations through the FinalizationRegistry support generated by wasm-bindgen, but that cleanup is nondeterministic.

For best performance, explicitly free short-lived Clockwork resources when you are done with them. Leaving many WASM-backed objects for the garbage collector can defer the cleanup and then run finalizers in expensive bursts of CPU usage.

const distanceMap = bfsMultiroomDistanceMap(start, {
  costMatrixCallback: room => getTerrainCostMatrix(room),
  maxRooms: 2
}).distanceMap;

try {
  const path = distanceMap.pathToOrigin(target);
  try {
    return path.toArray();
  } finally {
    path.free();
  }
} finally {
  distanceMap.free();
}

After free() is called, the wrapper is unusable. Calling methods on a freed Clockwork wrapper will throw.

Use free() for resources that are created and discarded quickly:

It’s still fine to keep long-lived objects, such as cached terrain cost matrices or reusable flow fields, for as long as they are useful. Ideally, free them when the cache entry is evicted or the data is no longer needed.

Finalizers are a safety net, but aren’t the optimal cleanup path for hot code.