What is WebAssembly and how does it work?
Is it really lighting fast as its introduction states?
Let's start with the first question.
What Is WebAssembly?
WebAssembly is a low-level, compiled language that can be run on all major browsers. It is pretty new so its effects are not very obvious on the websites we use daily.
The other innovation that comes with WebAssembly is the availability of languages such as C, C++, Rust, or TypeScript on the web. Since WebAssembly is very low-level, it is kind of hard to code. Fortunately, there are compilers that compile the languages I mentioned down to WebAssembly. So, you can use your favorite language on the web to develop web applications.
Here is a sum function written in TypeScript. Since we will compile this function to WebAssembly, type definitions should be accordingly (AssemblyScript).
An AssemblyScript function to add two numbers.
As you see, it is pretty understandable and readable by humans since TypeScript is a high-level language. Now we will convert this TypeScript function to WebAssembly.
This WebAssembly code seems complicated for most of the developers out there even though its logic is pretty simple, adding two numbers. That's why we don't write WebAssembly directly and rather use some other languages.
Is it really lighting fast as stated in its introduction?
I created a benchmark suite to test the addition of two numbers as follows.
Let's create another Fibonacci function to see if this is dependent on the function we use. As a parameter, I will use 3.
Fibonacci sequence until 3 using WASM and JS.
Then, let's make our benchmark with very complicated computation and see if the results are the same. I won't be creating a more complicated function, rather I will be using fibonacci again and make the parameter passed larger. Because the larger the parameter in the Fibonacci sequence, the more time the computation takes. So, I chose the parameter as 25.
If you want to try WebAssembly, you can use WebAssembly Studio to experience it online. For further you can visit the official website of WebAssembly.
Thank you guys for reading. In this story, we compared WASM with JS in terms of performance and probabilities.