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" .
GOOS=js GOARCH=wasmasks Go for Wasm that runs in a JavaScript environment (a browser or Node). This lesson uses Go 1.27.2.js.FuncOfwraps a Go function as a JS function, andjs.Global().Setputs it onglobalThis. Arguments arrive asjs.Value, so numbers are read with.Int().CopyBytesToGoandCopyBytesToJScopy the photo bytes from theUint8Arrayinto Go's memory and back again.select {}makesmainwait forever. Ifmainreturns, the Go program stops and the functions it registered die with it.wasm_exec.jsis the glue code: this module asks for 21gojsimports (clock, timers, access to JS objects), andwasm_exec.jsprovides them. Since Go 1.24 the file lives inlib/wasm; before that, inmisc/wasm.
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 |
- It is smaller because TinyGo's runtime is simple (a small garbage collector and scheduler), and LLVM removes every piece of code that is never called.
- The price: not every standard package or
reflectfeature is supported, and its garbage collector is slower for programs that allocate a lot. - Without
-no-debug, debug info (DWARF) is kept in the file. That is where the 236,916 bytes come from. -target=wasmneeds TinyGo's ownwasm_exec.js(17,729 bytes), not Go's.- A
wasm-unknownmodule can be instantiated with no glue at all, as long as_initialize()is called first. The Lab on this page runs that 2,567-byte module.
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
});
EMSCRIPTEN_KEEPALIVEkeeps a function from being removed by the optimiser and exports it. The other way, without touching the C code:-sEXPORTED_FUNCTIONS=_stayPrice,_grayscale. C names there get a leading underscore, and so do they in JS (M._stayPrice).-sMODULARIZE -sEXPORT_NAME=createPricemakesprice.jsdefinecreatePrice(), which returns a Promise of the module._malloc,_freeandHEAPU8have to be asked for, because JS needs all three to place a photo in C's memory.ccallcalls a C function by its name.- The result is two files:
price.wasmat 7,174 bytes (malloc comes in) andprice.jsat 10,511 bytes. Without_mallocand the runtime methods,emcc price.c -O2 -o price.jsis just 426 bytes plus 6,424 bytes of glue.
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
-nostdlib: no libc.-Wl,--no-entry: there is nomain.memoryis exported automatically.__heap_baseis the first address after C's stack and data. In this build it is 65,536, exactly the end of the initial memory (1 page). So JS has tomemory.growbefore placing the photo there; without it,setfails withRangeError: offset is out of bounds.- The result is 363 bytes, with no imports. You handle the JS side yourself: grow,
new Uint8Array(memory.buffer).set(photo, ptr), thengrayscale(ptr, photo.length).
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:
- Standard Go: existing Go code that needs the standard packages and goroutines, where a file of about 2 MB is acceptable.
- TinyGo: small Go modules for the browser, the edge or plugins, as long as TinyGo supports the packages.
- Emscripten: bringing large C/C++ libraries to the web (SQLite, ffmpeg, game engines). It provides a libc, a virtual file system and OpenGL through WebGL.
- Plain clang: small C functions without libc, when the file must be as small as possible and you are ready to manage the memory yourself.
⚠️ The required step each toolchain makes easy to forget
- Forgetting
select {}in Go'smain.mainreturns, the runtime stops, and the next call fails:Error: Go program has already exited. - A
wasm_exec.jsfrom another version. Copy it from the same Go that compiled the module. For TinyGo, use TinyGo'swasm_exec.js. The two cannot be swapped. - Forgetting
_initialize()on a TinyGowasm-unknownmodule. The runtime is not ready, andstayPricestops withRuntimeError: unreachable. - Forgetting
EMSCRIPTEN_KEEPALIVEor-sEXPORTED_FUNCTIONS. With-O2the function is removed:TypeError: M._stayPrice is not a function. ForgettingHEAPU8inEXPORTED_RUNTIME_METHODS: an-O0build stops withAborted('HEAPU8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)), an-O2build just givesundefined. - Overflow in C.
stayPrice(700000, 3500)comes out as-1844967296as in WAT, but in C a signedint32_toverflow is undefined behaviour: the compiler may assume it never happens. For big numbers useint64_t.
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.