WebAssembly: Grow Memory
Memory growth is the act of adding pages to a module's memory. The memory.grow call adds pages and returns the old page count.
Grow by one page in Wasm
This module starts with one page. Its grow function adds one more page.
(module
(memory (export "memory") 1)
(func (export "grow") (result i32)
(i32.const 1)
(memory.grow)))Check the size before growing
One page holds 65536 bytes. So the buffer starts at 65536.
console.log(instance.exports.memory.buffer.byteLength);Grow and check the size again
Grow returns 1, the old page count. The buffer is now 131072 bytes.
console.log(instance.exports.grow());
console.log(instance.exports.memory.buffer.byteLength);Example
(async () => {
const B64 = "AGFzbQEAAAABBQFgAAF/AwIBAAUDAQABBxECBm1lbW9yeQIABGdyb3cAAAoIAQYAQQFAAAs=";
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes);
console.log(instance.exports.memory.buffer.byteLength);
console.log(instance.exports.grow());
console.log(instance.exports.memory.buffer.byteLength);
})();Key points
- Memory growth adds pages to a module's memory.
- Each new page adds 65536 bytes.
- Memory.grow takes the number of pages to add.
- Memory.grow returns the old page count.
- Read buffer.byteLength again after a grow.
In this example, the bytes are decoded and started into an instance. Then the code logs the buffer size, which starts at 65536. Grow adds one page and returns 1, the old page count. Then the code logs the buffer size again, which is now 131072.
Note
An old typed array view goes stale after a grow.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does memory.grow return?