Extra: WebAssembly (Wasm)

While HTML, CSS, and JavaScript form the core of web development, a new technology called WebAssembly (Wasm) is changing the game for performance-critical applications. Think of it as a low-level, high-performance runtime for the web. It allows you to run pre-compiled code from languages like C, C++, and Rust directly in the browser, offering near-native speed.

Here is a simple example to illustrate how it works:

Step 1: The C code

Let's say you have a computationally intensive function in a C file, fib.c, that you want to run efficiently in your web page.

// fib.c
int fibonacci(int n) {
    if (n <= 1) {
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

Step 2: Compiling to Wasm

You can use the Emscripten toolchain to compile this C code into a Wasm module and the necessary JavaScript "glue code" to load it.

emcc fib.c -o fib.js -s EXPORTED_FUNCTIONS='["_fibonacci"]' -s WASM=1

This command generates fib.wasm, the binary Wasm module, and fib.js, a small script to help you load it.

The fib.js file is the "glue code" generated by Emscripten, which provides a higher-level JavaScript API for working with the WebAssembly module. While it can be useful in more complex scenarios, the following simple example bypasses it by interacting directly with the .wasm file using the native WebAssembly API.

Step 3: Using Wasm in your HTML

Now, you can load and run the compiled Wasm function directly within your HTML file using a bit of JavaScript.

<!DOCTYPE html>
<html>
<head>
    <title>WebAssembly Example</title>
</head>
<body>
    <h1>Fibonacci with WebAssembly</h1>
    <p>The result for Fibonacci(10) is: <span id="result"></span></p>

    <script>
        const resultElement = document.getElementById('result');

        // Fetch and instantiate the Wasm module
        WebAssembly.instantiateStreaming(fetch('fib.wasm')).then(result => {
            const exports = result.instance.exports;
            
            // Call the fibonacci() function compiled from C
            const fibResult = exports.fibonacci(10);
            
            // Display the result on the page
            resultElement.textContent = fibResult;
        });
    </script>
</body>
</html>

This simple example demonstrates a key application of Wasm: running high-performance code on the client side, which is perfect for tasks like gaming, scientific simulations, or video encoding directly in the browser. It complements JavaScript by providing a pathway for code that requires maximum performance.

WebGPU and the future of ML in the browser

Last updated

Was this helpful?