Wasm from Go / C++ — WebAssembly

Standard Go (GOOS=js GOARCH=wasm with syscall/js, js.FuncOf, select {}, and wasm_exec.js from lib/wasm of the same Go) produces 2,042,356 bytes for stayPrice…

Through wasm-pack, stayPrice and grayscale in Rust came to 14,896 bytes. What if your team is more at home in Go, or has old C code it wants to bring to the browser? Go and C/C++ can also be compiled to WebAssembly. The functions can be exactly the same, but what comes along inside the .wasm file differs enormously.

Say Mrs. Sri orders a layer cake for the guests of Mist Homestay from three shops. The first shop sends the cake together with a cook and a cleaner who move in with it. The second sends the same cake with one small helper. The third sends the cake alone, plus a slip of paper on how to serve it. The cake is the functions stayPrice and grayscale. The cook and the cleaner are the Go runtime (the goroutine scheduler and the garbage collector), the small helper is TinyGo's runtime, and the serving slip is Emscripten's JavaScript glue code.

Go: GOOS=js, GOARCH=wasm, and wasm_exec.js

The regular Go compiler can produce Wasm directly. Go functions are handed to JavaScript through the syscall/js package:

// main.go
package main

import "syscall/js"

func stayPrice(nights, pricePerNight int32) int32 {
	return nights * pricePerNight
}

func grayscale(px []byte) {
	for i := 0; i+3 < len(px); i += 4 {
		gray := byte((uint32(px[i])*77 + uint32(px[i+1])*150 + uint32(px[i+2])*29) >> 8)
		px[i], px[i+1], px[i+2] = gray, gray, gray
	}
}

func main() {
	js.Global().Set("stayPrice", js.FuncOf(func(this js.Value, args []js.Value) any {
		return stayPrice(int32(args[0].Int()), int32(args[1].Int()))
	}))
	js.Global().Set("grayscale", js.FuncOf(func(this js.Value, args []js.Value) any {
		buf := make([]byte, args[0].Get("length").Int())
		js.CopyBytesToGo(buf, args[0]) // copy the Uint8Array into a Go slice
		grayscale(buf)
		js.CopyBytesToJS(args[0], buf) // copy the result back
		return nil
	}))
	select {} // never let main finish
}
$ GOOS=js GOARCH=wasm go build -o price.wasm .
$ cp "$(go env GOROOT)/lib/wasm/wasm_exec.js" .

On the page: const go = new Go(), then WebAssembly.instantiateStreaming(fetch('price.wasm'), go.importObject), then go.run(instance). After that, stayPrice(2, 3500) returns 7000.

The result: price.wasm is 2,042,356 bytes (593,144 bytes gzipped). Nearly all of it is the Go runtime: the garbage collector, the goroutine scheduler and the syscall/js support. Crossing is expensive too: every call through js.FuncOf wakes up the Go scheduler. In Node 22, 100,000 calls to stayPrice take about 780 ms. 100,000 calls to a plain Wasm export (from TinyGo or C below) take about 0.7 ms.

📌 Go without syscall/js: GOOS=wasip1 and //go:wasmexport

Go 1.21 added the GOOS=wasip1 target (WASI Preview 1, a system interface for Wasm outside the browser). Go 1.24 added the //go:wasmexport directive, which exports a Go function directly as a Wasm export, and -buildmode=c-shared for a library (reactor) module that does not run main:

//go:wasmexport stayPrice
func stayPrice(nights, pricePerNight int32) int32 {
	return nights * pricePerNight
}

GOOS=wasip1 GOARCH=wasm go build -buildmode=c-shared -o price.wasm . produces 1,931,836 bytes with 10 wasi_snapshot_preview1 imports (clock, random numbers, writing to stdout and more). In Node those imports come from node:wasi, and wasi.initialize(instance) must be called before stayPrice. For grayscale the module exports allocBuffer(n), so JS writes the photo into space Go reserved itself. The size stays around 2 MB, because the runtime is the same.

TinyGo: the same Go, a far smaller file

TinyGo is a different Go compiler built on LLVM. The same code, built with TinyGo 0.43.0:

Command .wasm size
tinygo build -target=wasm -o price.wasm . (the syscall/js version) 236,916 bytes
the same, plus -no-debug 54,371 bytes
tinygo build -target=wasip1 -buildmode=c-shared -no-debug ... 27,767 bytes
tinygo build -target=wasm-unknown -no-debug ... 2,567 bytes, 0 imports

C with Emscripten

Emscripten is a C/C++ to Wasm toolchain: the emcc compiler (built on clang/LLVM), a libc, and JavaScript glue code that imitates a C environment (a heap, a virtual file system, OpenGL through WebGL). This lesson uses Emscripten 6.0.12.

// price.c
#include <emscripten.h>
#include <stdint.h>

EMSCRIPTEN_KEEPALIVE
int32_t stayPrice(int32_t nights, int32_t pricePerNight) {
  return nights * pricePerNight;
}

EMSCRIPTEN_KEEPALIVE
void grayscale(uint8_t *px, int32_t len) {
  for (int32_t i = 0; i + 3 < len; i += 4) {
    uint8_t gray = (px[i] * 77 + px[i + 1] * 150 + px[i + 2] * 29) >> 8;
    px[i] = gray;
    px[i + 1] = gray;
    px[i + 2] = gray;
  }
}
$ emcc price.c -O2 -sMODULARIZE -sEXPORT_NAME=createPrice \
    -sEXPORTED_FUNCTIONS=_malloc,_free -sEXPORTED_RUNTIME_METHODS=ccall,cwrap,HEAPU8 \
    -o price.js
createPrice().then((M) => {
  console.log(M._stayPrice(2, 3500)); // 7000
  console.log(M.ccall('stayPrice', 'number', ['number', 'number'], [2, 3500])); // 7000
  const ptr = M._malloc(4);               // reserve 4 bytes on the C heap
  M.HEAPU8.set([200, 120, 40, 255], ptr); // write one pixel
  M._grayscale(ptr, 4);
  console.log(M.HEAPU8.slice(ptr, ptr + 4)); // Uint8Array(4) [135, 135, 135, 255]
  M._free(ptr);                           // give it back to the heap
});

C without glue: clang --target=wasm32

clang can produce Wasm without Emscripten, as long as the code needs no libc. The Apple clang that ships with macOS has no Wasm target; use clang from LLVM, wasi-sdk, or the one inside emsdk. price-plain.c is price.c without #include <emscripten.h>, with each EMSCRIPTEN_KEEPALIVE replaced by __attribute__((export_name("stayPrice"))) (and "grayscale"):

$ clang --target=wasm32 -nostdlib -O2 -Wl,--no-entry -Wl,--export=__heap_base \
    -Wl,--strip-all price-plain.c -o price-plain.wasm

The sizes, measured

Every build holds stayPrice and grayscale with the same formula:

Build .wasm JS glue
Go 1.27.2, GOOS=js 2,042,356 bytes wasm_exec.js 16,992 bytes
Go 1.27.2, GOOS=wasip1, c-shared 1,931,836 bytes a WASI host
TinyGo 0.43.0, -target=wasm -no-debug 54,371 bytes wasm_exec.js 17,729 bytes
Rust + wasm-pack (the previous lesson) 14,896 bytes 5,313 bytes
Emscripten 6.0.12, with _malloc and HEAPU8 7,174 bytes 10,511 bytes
TinyGo 0.43.0, -target=wasm-unknown -no-debug 2,567 bytes none
clang 24, --target=wasm32 -nostdlib 363 bytes none

The Go version is more than 5,000 times bigger than plain clang: 2,042,356 divided by 363 is about 5,600. Nearly all of the difference is the Go runtime, not our functions, and even gzipped the Go version is still 593,144 bytes.

When to use which:

⚠️ The required step each toolchain makes easy to forget

TL;DR: Standard Go (GOOS=js GOARCH=wasm with syscall/js, js.FuncOf, select {}, and wasm_exec.js from lib/wasm of the same Go) produces 2,042,356 bytes for stayPrice and grayscale, because the Go runtime and garbage collector come along; calls through js.FuncOf are slow too. GOOS=wasip1 (Go 1.21) with //go:wasmexport and -buildmode=c-shared (Go 1.24) stays around 1.9 MB. TinyGo uses a small runtime and LLVM: from 54,371 bytes (-target=wasm -no-debug) down to 2,567 bytes (-target=wasm-unknown, call _initialize() first), with more limited package support. Emscripten (emcc) is the full C/C++ toolchain: EMSCRIPTEN_KEEPALIVE or -sEXPORTED_FUNCTIONS=_name, .js glue, and _malloc/HEAPU8/_free for data. clang --target=wasm32 -nostdlib without glue: 363 bytes, and you manage the memory yourself.

⚡ Go puts its functions on globalThis

Write:

func main() {
	js.Global().Set("stayPrice", js.FuncOf(func(this js.Value, args []js.Value) any {
		return stayPrice(int32(args[0].Int()), int32(args[1].Int()))
	}))
	select {} // never let main finish
}

Meaning: js.FuncOf wraps a Go function as a JS function, and js.Global().Set puts it on globalThis. Without select {}, main returns, the Go program stops, and the next call fails with Error: Go program has already exited.

⚡ Two megabytes for one multiplication

Guess first: stayPrice and grayscale are built with standard Go (GOOS=js). How big is the file?

2,042,356 bytes, and still 593,144 bytes gzipped. Nearly all of it is the Go runtime: the garbage collector, the goroutine scheduler and the syscall/js support.

Meaning: That is standard Go's biggest weakness for Wasm. The functions themselves are small; what is big is the runtime that comes along.

⚡ TinyGo and clang are far smaller

Meaning: The same Go code through TinyGo is 54,371 bytes, or 2,567 bytes with -target=wasm-unknown (call _initialize() first). clang --target=wasm32 -nostdlib is just 363 bytes, but you manage the memory yourself, memory.grow included.

⚡ Emscripten for big C/C++ code

Write:

$ emcc price.c -O2 -sMODULARIZE -sEXPORT_NAME=createPrice \
    -sEXPORTED_FUNCTIONS=_malloc,_free -sEXPORTED_RUNTIME_METHODS=ccall,cwrap,HEAPU8 \
    -o price.js

Meaning: Emscripten brings a libc, a virtual file system and OpenGL through WebGL. A C function needs EMSCRIPTEN_KEEPALIVE so the optimiser does not drop it, and _malloc and HEAPU8 have to be asked for so JS can place a photo in C's memory.

What you will learn