Skip to content

Avoid quadratic metadata scans during WebAssembly allocation #794

Closed

Description

@LunaStev

Problem

Allocating many small live objects through the wasm64 allocator takes approximately quadratic time. Every fresh allocation scans all live blocks in blocks_reuse, then scans them again in blocks_append to locate the tail. This affects workloads that build collections while retaining their elements, even without frees or fragmentation.

Starting points: std/sys/wasm_blocks.wave, std/sys/wasm64/memory.wave, std/sys/wasm/memory.wave. #700 introduced reuse/splitting/coalescing; this issue concerns traversal cost while preserving those behaviors.

Reproduction and measurement

Executed at 4c3372157d8889fa8bbef0a7ccd2e72aab1c5c6c with LLVM/wasm-ld 21.1.8, Node.js 22.22.1, Linux amd64 and an AMD Ryzen 5 2600X. Target: wasm64-unknown-unknown, O2. Each run uses a fresh module instance and requests 16-byte allocations. Compilation and instantiation are outside the timed region. One warmup round is excluded; five measured rounds follow for each size.

Prepare an alias of the matching checkout std from the repository root (this avoids using an older installed std):

python3 - <<'PYSETUP'
from pathlib import Path
out = Path(".tmp/additional-audit-std")
for source in Path("std").rglob("*.wave"):
    dest = out / source.relative_to("std")
    dest.parent.mkdir(parents=True, exist_ok=True)
    dest.write_text(source.read_text().replace('"std::', '"checkout_std::'))
PYSETUP

Save as bench.wave:

import("checkout_std::sys::memory")::{sys_alloc};
export(c) fun bench(count: i32) -> i32 {
    var i: i32 = 0;
    while (i < count) {
        var p: ptr<u8> = sys_alloc(16);
        if (p == null) { return -1; }
        deref p = 42;
        i += 1;
    }
    return i;
}
fun main() -> i32 { return 0; }

Save as measure.mjs:

import {readFileSync} from 'node:fs';
import {performance} from 'node:perf_hooks';
const module = await WebAssembly.compile(readFileSync(process.argv[2]));
const results = {};
for (let trial=0;trial<6;trial++) {
  for (const n of [4000,8000,16000]) {
    const instance = await WebAssembly.instantiate(module,{});
    const start=performance.now();
    const result=instance.exports.bench(n);
    const ms=performance.now()-start;
    if(result!==n)throw Error(`allocation failed: ${result}`);
    if(trial>0)(results[n]??=[]).push(ms);
  }
}
console.log(JSON.stringify({node:process.version,samples_ms:results},null,2));
target/debug/wavec build bench.wave --dep checkout_std=.tmp/additional-audit-std --target wasm64-unknown-unknown -O2 --out-dir .tmp/allocator-bench
node --experimental-wasm-memory64 measure.mjs .tmp/allocator-bench/bench.wasm

Results

Live allocations Median (ms) Range (ms)
4,000 20.76 20.05–22.36
8,000 82.46 82.24–83.19
16,000 342.00 340.30–343.23

Doubling allocations increases median time about fourfold. These are scaling measurements of the current allocator, not a comparison against a proposed implementation. All runs successfully allocated the requested count.

Scope

Avoid repeated full traversal of the live-block list on the fresh-allocation path. Preserve allocation ownership, 16-byte alignment, splitting/coalescing, size validation and handling of memory grown externally. The metadata is shared by wasm32 and wasm64; measured runtime evidence here is wasm64 only.

Difficulty: medium.

Completion criteria

  • Repeat the scaling benchmark and show the no-free allocation path no longer performs quadratic metadata traversal.
  • Retain correctness coverage for mixed allocation/free workloads, reuse, splitting/coalescing, invalid frees and external memory growth.
  • Exercise the shared change under both memory32 and memory64 runtimes; report timing variability rather than enforcing a machine-specific millisecond threshold.

Activity

  1. added
    help wanted
    performance
    on Sep 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedperformance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions