WebAssembly SIMD: One Instruction, Four Numbers
SIMD runs one instruction on four numbers at once. A SIMD lane is one of those four numbers.
Add four lanes at once
This function adds two sets of four lanes, then adds the four lanes together.
(module
(func (export "simdSum") (result i32)
(local v128)
v128.const i32x4 1 2 3 4
v128.const i32x4 10 20 30 40
i32x4.add
local.set 0
(i32.add
(i32.add
(i32x4.extract_lane 0 (local.get 0))
(i32x4.extract_lane 1 (local.get 0)))
(i32.add
(i32x4.extract_lane 2 (local.get 0))
(i32x4.extract_lane 3 (local.get 0))))))Add four numbers in Rust
Rust turns this short code into SIMD on its own.
fn add_all(a: &[i32; 4], b: &[i32; 4]) -> [i32; 4] {
[a[0] + b[0], a[1] + b[1], a[2] + b[2], a[3] + b[3]]
}Example
const B64 = "AGFzbQEAAAABBQFgAAF/AwIBAAcLAQdzaW1kU3VtAAAKRgFEAQF7/QwBAAAAAgAAAAMAAAAEAAAA/QwKAAAAFAAAAB4AAAAoAAAA/a4BIQAgAP0bACAA/RsBaiAA/RsCIAD9GwNqags=";
(async () => {
const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
const { instance } = await WebAssembly.instantiate(bytes, {});
console.log("SIMD sum:", instance.exports.simdSum());
})();Key points
- SIMD is a 128-bit instruction that handles four numbers together.
- Use one v128 value to hold four 32-bit lanes.
- Chrome 91 and Firefox 89 shipped SIMD support.
- Images and audio gain most from SIMD speedups.
- Rust turns short loops into SIMD code on its own.
- Intrinsics: special function names that ask for SIMD directly.
- C++ uses intrinsics to ask for SIMD directly.
- One instruction can add four numbers at once.
In this example, the code decodes the module bytes from B64 and instantiates the module. It calls simdSum and logs the result. The module adds the two lane sets with one SIMD add, then it sums the lanes. 11 plus 22 plus 33 plus 44 is 110.
Note
SIMD needs a browser that supports the 128-bit type.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does one SIMD instruction add?