Sikau

WebAssembly · Day 9 · about 40 min

Memory in depth: pages, growth and byte order

Grow memory safely, mind detached views and read numbers in the right byte order.

The shop shelf that moves

Imagine a momo shop in Pokhara with one long shelf. Every item has a number: shelf slot 0, slot 1, slot 2. Now the owner decides the shelf is too small and swaps it for a longer one. Anyone still holding a note that says "I am looking at the old shelf" is now looking at an empty wall. WebAssembly memory behaves exactly like that.

A module's linear memory is a flat run of bytes whose size is counted in pages of 64 KiB. JavaScript sees it as an ArrayBuffer. When wasm asks for more memory, the engine may need to allocate a bigger buffer, so the old ArrayBuffer is detached and every typed array made from it turns into a view of length 0.

Pages, limits and grow

You can create memory from JavaScript: new WebAssembly.Memory({ initial: 1, maximum: 4 }). The numbers are pages, not bytes, so this memory starts at 65,536 bytes and may never pass 262,144. memory.grow(n) adds n pages and returns the previous page count, which is handy: the old count times 65,536 is the address where the new space begins.

const memory = new WebAssembly.Memory({ initial: 1, maximum: 2 });
const before = new Uint8Array(memory.buffer);
console.log(before.length);
console.log(memory.grow(1));
console.log(before.length);
const after = new Uint8Array(memory.buffer);
console.log(after.length);
try { memory.grow(1); } catch (e) { console.log(e.name); }

Treat every typed array over memory.buffer as short-lived. Fetch memory.buffer again after any call into wasm that might allocate.

The rest of this lesson

  • Byte order and alignmentexplain
  • Which size does the old view report?predict
  • Grow memory safelyorder
  • Memory vocabularymatch
  • Work with real memorywrite code
  • Badge quizquiz
  • What you learnedrecap