Shared Memory

Learn how to use memory in WebAssembly.

We'll cover the following

Transferring data between JavaScript and WebAssembly is an expensive operation. In order to reduce the transfer of data between JavaScript and WebAssembly modules, WebAssembly uses sharedArrayBuffer. With sharedArrayBuffer both the JavaScript and WebAssembly modules can access the same memory and use it to share data with each other.

The memory section of a WebAssembly module is a vector of linear memories. The linear memory model is a memory-addressing technique in which the memory is organized in a single contiguous address space. It’s also known as a flat memory model. The linear memory model makes it easier to understand, program, and represent the memory. But the linear memory model comes with the huge disadvantage of a high execution time for rearranging elements in the memory, and it also wastes memory space. Here, the memory represents a vector of raw bytes of uninterpreted data. They use resizable array buffers to hold the raw bytes of memory. We use sharedArrayBuffers for defining and maintaining this memory.

Note: It’s important to note that this memory is accessible and mutable by JavaScript and WebAssembly.

We allocate the memory using the WebAssembly.Memory() constructor. The constructor can accept an argument that defines the initial and maximum value of memory:

Get hands-on with 1400+ tech skills courses.