Wasm enables us to compile C/C++ code to a binary format that can be executed directly by the browser. As a result the code may execute as fast as native machine code. In most everyday web application this extra boost in performance may not mean much in practice, but still, it makes for a fun experiment :-)
Since this is my first time playing with wasm, I won’t attempt anything fancy. Instead I will keep it simple and implement a recursive version of n-factorial in C++.
It’s probably overkill to do an object oriented implementation of this, but I went ahead and did one anyway. Mainly because I wanted to test out a multi file integration.
Here is the C++ code:
For the most part this looks like regular C++ code… Or at least how I remember it from my C++ courses close to 20 years ago :-)…
The only exception might be the extern "C" int factorial(int n) part. This is done to prevent the C++ compiler from mangling the function name into something unpredictable.
Now that we have some C++ code, how do we compile it?
For this experiment I will be using the Emscripten compiler, which seems to be a popular choice btw. Most examples I could find used Emscripten.
I am not aware of an IDE, but running Emscripten from the command line works just fine. Here is the command I used to compile the C++ code:
The output from the compiler is a .wasm file and a .js file. The wasm file is where you will find the compiled C++ code.
I didn’t expect a huge difference in performance here, but my measurements showed that the C++ version is consistently faster. I measured an average difference of 10-20% when running with large values of n in a long running loop.