WebAssembly is an open standard that allows the execution of binary code on the web. This standard, or format code, lets developers bring the performance of languages like C, C++, and Rust to the web development area. This technology is commonly used to perform demanding operations in the browser.
WebAssembly, or WASM, is a binary code format close to assembly and independent of the language and the platform since WebAssembly can be compiled from other languages and can be executed on a browser (Web APIs) or a virtual machine. WebAssembly is an open standard whose main objective is to offer a closely native performance on the web while maintaining compatibility with the current ecosystems and standards.
Before we start digging into WebAssembly, we need to familiarize ourselves with some basic concepts around this code format to understand how it runs on the browser.
WebAssembly is organized into modules compiled in binary by the browser (or virtual machine). They can be seen the same way as ECMAScript modules, where modules contain functions and can import and export other functions.
WebAssembly is a stack machine because it works under a system of instructions (ISA). These instructions allow the control of the loops, arithmetic operations, and memory access.
In order to facilitate everything as much as possible, we are going to use WebAssembly Studio. This tool is an online editor for WebAssembly that allows us to create WASM projects in a variety of languages (WAT, Rust, C, AssemblyScript, etc.).
So in order to be able to use the API, our first step is to load our WASM file as a resource. We can do this using a basic fetch.
Now we need to download the WASM file and compile it to get the WASM module. This step can be solved differently but we are going to use the instantiateStreaming method. Then we retrieve the instance from that module to be able to access the multiply function created on our WASM file.
WebAssembly was made to improve performance on heavy tasks and one example of this can be image manipulation. So to test this, we’ll take the pixel manipulation with canvas example from MDN and add the same function to invert pixel colors but using WASM. This example is using the ImageData object to manipulate the pixels of a canvas.
In this example, WebAssembly once again is faster, showing an improvement of 50 - 60% for average on each execution. This does not mean that everything we do in WebAssembly will always have these performance differences.
Then to use it on our AssemblyScript file, we should declare the function before we use it.
WebAssembly is becoming more and more important for web development and is a great tool to improve applications for our clients. If you are interested in joining our team, please visit our careers page.
We’d love to learn more about your project.
Engagements start at $50,000.