Analyzing the Memory Model in the WebAssembly Module

Learn how to use memory in the WebAssembly module.

Inside the JavaScript engine, WebAssembly and JavaScript run at different locations. Crossing the boundaries between JavaScript and WebAssembly will always have a cost attached to it. The browser vendors implemented cool hacks and workarounds to reduce this cost, but when your applications cross this boundary, it will often become a major performance bottleneck for your application. It’s very important to design WebAssembly applications in a way that reduces boundary crossing. But once the application grows, it becomes difficult to manage such boundary crossing. To prevent boundary crossing, WebAssembly modules come with the memory module.

The memory section in the WebAssembly module is a vector of linear memories. A 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 the flat memory model. The linear memory model makes it easier to understand, program, and represent the memory. But it also has huge disadvantages, such as a high execution time for rearranging elements in memory and the waste of a lot of memory area.

Here, the memory represents a vector of raw bytes containing uninterpreted data. WebAssembly uses resizable array buffers to hold the raw bytes of memory. It’s important to note that this memory that’s created is accessible and mutable from both JavaScript and WebAssembly.

Getting started with the project

We’ve already seen how to share the memory between JavaScript and WebAssembly. Let’s share memory using Rust in this example:

  1. Create a new Rust project using Cargo:

Get hands-on with 1200+ tech skills courses.