An open API service indexing awesome lists of open source software.

https://github.com/paralin/reuse-wasm-module-demo

Demonstrate re-using the same compiled wasm module across workers with structured clone
https://github.com/paralin/reuse-wasm-module-demo

Last synced: 8 months ago
JSON representation

Demonstrate re-using the same compiled wasm module across workers with structured clone

Awesome Lists containing this project

README

          

# WebAssembly Module Reuse Demo

This project demonstrates how to compile a WebAssembly module once and reuse it across multiple web workers, avoiding redundant compilation.

## What This Demonstrates

1. **Single WebAssembly Compilation**: The main thread compiles the WebAssembly module once using `WebAssembly.compileStreaming()`.
2. **Module Sharing**: The compiled module is shared with multiple web workers by sending the `WebAssembly.Module` object via `postMessage()`.
3. **Independent Instantiation**: Each web worker independently instantiates the module, creating its own isolated execution environment.
4. **Parallel Execution**: The same module is executed in parallel across different workers.

This approach offers several advantages:

- Reduced memory usage by compiling the WebAssembly binary only once
- Faster startup time for additional workers since compilation is skipped
- Same code can be executed safely in parallel across multiple workers

## Technologies Used

- **AssemblyScript**: TypeScript-like language that compiles to WebAssembly
- **Web Workers**: For parallel execution
- **WebAssembly API**: Using the streaming compilation API for better performance
- **Cross-Origin Isolation**: Enabled via COOP/COEP headers to support SharedArrayBuffer

## Running the Demo

1. Install dependencies:

```
npm install
```

2. Build and run:

```
npm run build
```

3. Open http://localhost:5173 in your browser

The demo will load a WebAssembly module containing two functions:

- A simple "Hello World" string function
- A Fibonacci calculation function

These functions will be executed in separate web workers to demonstrate parallel execution of the same module.

## Implementation Details

The main thread:

1. Fetches and compiles the WebAssembly module using `WebAssembly.compileStreaming()`
2. Creates two web workers
3. Posts the compiled module to both workers via `postMessage()`
4. Sends execution commands to each worker

Each worker:

1. Receives the module reference
2. Independently instantiates it with its own memory and execution context
3. Executes functions from the module when requested
4. Returns results to the main thread

This pattern can be extended to create worker pools that share the same WebAssembly module but execute in parallel.