Why Javascript WeakRefs Will Unleash The Power of Web Assembly

Richard Anaya
2 min readJun 30, 2019

Let me tell you the story about two worlds. Javascript and Web Assembly. They are the two most powerful supported runtimes in browsers at the current moment with some serious trade offs:

Javascript

Pros

  • Can talk to the DOM directly
  • Is always the first thing that is executed in browsers
  • Can do multiple threads vs web work workers

Con

  • Very slow at math
  • Has very little control over memory management

Web Assembly

Pros

  • Supports a variety of languages
  • Extremely fast
  • Full control over memory

Cons

  • single process
  • no access to environment

Pretty much the only game in town right now for writing web experiences using WebAssembly requires holding onto handles to the host environment’s resources (i.e. an integer that represents a DOM element in a dictionary somewhere).

  1. Web Assembly calls out to an external function in javascript
  2. Javascript function creates a resource in the host environment and returns a handle
  3. Whenever web assembly needs to operate on that host environment resource, call an external function with that handle

4. External function implementation looks up resource with handle

It seems like a simple plan until you have to ask the question “how long should I store a mapping of a handle to an host resource?”

Right now Web Assembly in the browser is very restrained in its knowledge about things in the host environment, to know something is alive, it must keep a memory reference to it, but by keeping a memory reference to it, it will keep it alive.

In a perfect world, we have a very clear and direct lifetime on how long resources should be held for, but lets face it, in an async and multi threaded world, it’s easy to lose track of who is messing with what.

Rather than having strong handles to resources outside of your web assembly module, wouldn’t it be nice to point to things in the host environment and not have to worry about memory leaks if that resource gets trashed by some other operation?

This is where the value of weak references in Javascript start to shine. If implemented, that would allow you to hold onto things in the DOM loosely. If some command came through and trashed your whole DOM element tree or an error occurred making some object you were holding onto useless, you have an opportunity to see “Hey, this thing you were referring to disappeared” and respond to web assembly accordingly “Hey, this thing you thought existed does not anymore”.

I’m looking forward to seeing how web assembly frameworks evolve in a world where it can hold onto things loosely. If you have interest in seeing this evolve, be on the lookout for

--

--