Logo loophole letters

Running AssemblyScript on the Web

code

After running Lua on the Web, let’s try a faster alternative: AssemblyScript.

While lua scripts are interpreted by a wasm program, AssemblyScript programs directly compile to wasm, which should make them significantly faster.

Compilation

After some tinkering, reading the compiler docs + taking some bits from javascriptmusic (which btw inspired this whole idea), I’ve found this function to compile AssemblyScript code:

import asc from "assemblyscript/asc";

async function compileAssemblyScript(code) {
  const output = Object.create({
    stdout: asc.createMemoryStream(),
    stderr: asc.createMemoryStream(),
  });
  const sources = {
    "index.ts": code,
  };
  const { error } = await asc.main(
    ["--outFile", "binary", "--textFile", "text", "index.ts"],
    {
      stdout: output.stdout,
      stderr: output.stderr,
      readFile: (name) => (sources.hasOwnProperty(name) ? sources[name] : null),
      writeFile: (name, contents) => (output[name] = contents),
      listFiles: () => [],
    }
  );
  if (error) {
    throw new Error(error.message);
  }
  return output;
}

The above function outputs an object with a .binary, where the web assembly binary is located as a buffer. We can instantiate that using the browser method

const output = await compileAssemblyScript(`
function fib(n: i32): i32 {
  if(n<2) {
    return 1;
  }
  return fib(n-1) + fib(n-2);
}
export function main(): i32 {
  return fib(36)
}
`);
const wasm = await WebAssembly.instantiate(output.binary, {});
const main = wasm.instance.exports.main;
console.log(main()); // 24157817

With this knowledge, creating an AssemblyScript REPL is possible:

This seems to run quite fast!

Versus JavaScript

Let’s compare it to the JavaScript:

ms

Not really surprising, but still great to see that AssemblyScript is faster! For lower values of n, it’s slower, but that is only because the compilation takes a bit of time. The actual script execution is way faster.

And yes, of course there are faster fibonacci implementations, but that’s not the point:

I am eager to try out writing DSP with AssemblyScript, which should pair nicely with AudioWorklet, to create faster-than-javascript performance! Thanks to Peter Salomonsen’s javascriptmusic for inspiring the idea.

❤️ 2024 Felix Roos | mastodon | github