Skip to content

Elimination of manual memory management (by default and/or within an init option) via JavaScript's FinalizationRegistry/WeakRef? #115

@josephrocca

Description

@josephrocca

Here are the relevant MDN docs:

My understanding is that using FinalizationRegistry, it would look something vaguely like this:

const finalizationRegistry = new FinalizationRegistry(wasmRef => {
  // the JS-level Vec3 instance has been garbage collected, so deallocate the emscripten-level stuff
  deallocateTheThing(wasmRef);
});

export class Vec3 {
  constructor(x, y, z) {
    // create wasmRef, etc ...
    finalizationRegistry.register(this, wasmRef); // this tells the runtime to watch for when `this` is garbage collected, and when it is, call the registry callback (defined above) with `wasmRef` as the argument
  }
  // ...
}

// Note: The same finalization registry instance can be used for the whole Jolt module/engine IIUC.

So that instead of this:

let material = new Jolt.PhysicsMaterial();
let size = new Jolt.Vec3(4, 0.5, 0.5);
let box = new Jolt.BoxShapeSettings(size, 0.05, material);
Jolt.destroy(size);
// ...

We can just write this:

let material = new Jolt.PhysicsMaterial();
let size = new Jolt.Vec3(4, 0.5, 0.5);
let box = new Jolt.BoxShapeSettings(size, 0.05, material);
// ...

If it'd somehow be a non-trivial perf hit or a breaking change, then maybe some sort of init option? (If my opinion is at all useful here, I think it should be default)

I'm currently using Rapier for a project and it's been great in terms of JS idiomaticity (I guess Rust's wasm-pack handles memory stuff automatically?), so I'm just posting this in the hopes that Jolt can get to a similarly pleasant DX. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions