Tech Insights
Kanishka Dilshan
December 7, 2015

Struggling to deliver sprints on time

Struggling to deliver sprints on time

Introduction

WebAssembly(Wasm) is an official W3C open web standard for highperformance web applications. It is the 4th language (Javascript, HTML &CSS) to run on browsers as recognised by the W3C. Webassembly is safe, compact,hardware independent, open and accepted by all the major browsers. It is not alanguage that developers may directly work on, but a portable compile targetfor other high level languages like C/C++ and Rust, which means, developers cancompile their existing code into Webassembly if their compiler supports.

Wasm instructions are in very concise binary formats that can be loadedover the internet and executed by the Wasm virtual machine.

In this article we’ll discuss when webassembly shines and how to compilea C programme into Webassembly and run it on almost any browser.

Problem with JavaScript

JavaScript is not designed for performance in mind. It is designed forsimplicity & multi paradigm. Optimisations are done by the executionengines such as V8.

When a JavaScript programme is being executed in a browser it has topass multiple stages before actually being executed its instructions (fig.1.0). Also there is a garbage collector to release allocated memory. So theprogramme is subjected to GC pauses as well.

Furthermore there is a profiler in action keeping statistics of executedcode which contributes to relatively higher memory consumption.

The following diagram depicts how V8 engines executes JavaScript.

                         

Attempts to fix JS performance issues

In addition to execution engine enhancements, following actions aretaken to overcome the performance issues in JS.

·        Optimisers (e.g. prepack, jso)

·        Minifiers

·        Following rules & conventions

Since JavaScript was the one andonly programming language accepted by W3C at that time, different browserruntimes were produced to fill the vacuum.

History of browser runtimes

Due to these issues and lack of flexibility different vendors tried to addressthose issues in their own way by providing different browser runtimes. Butnothing was accepted by W3C as a web standard.

·        ActiveX

·        Java Applets

·        Flash

·        Silverlight

·        Google NaCl

How WebAssembly solves these issues

Now web assembly is an open standard. So it will be maintained carefullyand continue for quite a while. On other hand, Wasm doesn’t require users toinstall additional runtimes on the browser. It will be available on webbrowsers by default. So the security and other critical updates are directlypushed by the browser vendor.

When it comes to performance, Wasm has a number of advantages.

·        Small in size

·        It is already compiled & optimisedby a compiler. As a result the Wasm artifact is quite concise so it can bequickly loaded by the client programme. This will ultimately improve the loadtime.

·        Less overhead

·        It doesn’t require a garbage collector.The language supports managing memory manually.

·        No parser required because Wasm code iscloser to the machine code. So it is just decoded by the WebAssembly VM. ButJavaScript VM has to generate the abstract syntax tree (AST) before preparingfor the execution.

·        Fast execution

·        Wasm code does not require optimisationsas it is already optimised by the compiler. So optimise/deoptimise the code inthe runtime is not a requirement anymore. Which means there is no need for aprofiler as well.

·        Low memory footprint

·        With the absence of the profiler andother runtime optimisation mechanisms, execution of a Wasm code requiresrelatively low amount of memory.

Use Cases for Wasm

There are no silver bullets. Each technology has its own sweet spot. Thepower of WebAssembly can be utilised well in below scenarios.

·        3D & 2D Games

·        Audio/Video streaming

·        Fast audio/video codecs

·        Image recognition

·        Compression

·        Crypto functions

·        Reusing existing C/C++ libraries on theweb

·        Port existing apps as browser basedapplications (i.e. Autocad Web)  

·        Learn more

Architecture

WebAssembly is a virtual CPU which supports machine instructions closerto assembly instructions. But Wasm instructions are hardware/softwareindependent (portable) & safe (sandboxed).

                                                                     

With the current Wasm version there is no direct access to the web APIssuch as DOM or Ajax. It should achieve this via JS. In the future WebAssemblymight be given direct access to the web APIs.

Browser Support

All the major browsers support WebAssembly. Couple of Android browsersand Old Internet Explorer that has reached the end of life, don’t support Wasm.Since it is a W3C standard we can expect Wasm to be supported everywhere on theweb

                             

Development with WebAssembly

As I mentioned before we don’t programme directly in Wasm. Rather,developers choose a language where WebAssembly is supported as a compile targeti.e. C/C++, Rust, Golang (experimental) and a WebAssembly toolchain i.e. Emscripten, LLVM, binaryen, wabt.

A basic WebAssembly development workflow is depicted below.

                                                               

To demonstrate this I will write a function to calculate Fibonacci valuefor a given number and return.

Setting up the Toolchain

Below are the instructions to set up the Emscripten WebAssemblytoolchain on Linux. For other platforms please refer to this.

git clone https://github.com/emscripten-core/emsdk.git

cd emsdk/

./emsdk install latest

./emsdk activate latest

source ./emsdk_env.sh --build=Release #[or add this to ~/bashrc]

Write a simple programme in C

For the sakeof simplicity I am writing this programme in C.

hello.c

[https://gist.github.com/kdkanishka/1b1cd8b05340e56b267c78e34fbc8bab]

Note: In thecompilation process emscripten compiler ignores the unused methods. Since thefib() method is not used by any other function at the compile time, we need to“annotate” this function with EMSCRIPTEN_KEEPALIVE so the compilerdoesn’t ignore the function.

Compiling a C programme as a WebAssembly target

emcc hello.c -o hello.html -sEXTRA_EXPORTED_RUNTIME_METHODS='["cwrap"]'

If the programme compiles successfully, Itshould generate the WebAssembly programme as “hello.wasm”

Also it generates a JavaScript (hello.js) filewhich is the glue code or proxy for the fib() function. The project directoryshould look like this now.

                                             

WebAssembly Interoperability with JS

In order tocall the WebAssembly function from JavaScript, we should load the WebAssemblyprogramme and create a wrapper to access that function. This can be donemanually or we can use the generated gluecode (hello.js). In this example I amimporting the generated glue code to keep the demo simple.

A functionwrapper can be created for the fib function with the statement below.

var fibProxy = Module.cwrap("fib", "number", ["number"]);

Now we can use the fibProxy object to invokefib() function that we have already compiled to Wasm.

Let’s complete the programme...

We are going to create a wrapper for the fib()function and use it in below web page.

demo.html

[https://gist.github.com/kdkanishka/cb9b46e69b8b10bc838662fc1f0312fa]

Now we have a complete programme. Let's run ourdemo web site.

Execute the following command in the projectdirectory to create a small web server to serve our web page.

emrun --no_browser --port 8080

Now visit https://localhost:8080/demo.html

Output

                                                   

This way we can write CPU intensive sections ofour web applications in web assembly. It is also possible to access JavaScriptfunctions from web assembly.

The best example is https://web.autocad.com/, the web version of AutoCad. They have lots of modeling and involve lotsof calculations. So far they have had a desktop application. But with the riseof WebAssembly they could easily port their desktop application to the web.

Frameworks for WebAssembly

Blazor is a framework whichsupports WebAssembly on either browser or the server and is developed byMicrosoft. With Blazor developers can write both frontend and backend in C#.

They have achieved this by porting the mono runtime to WebAssembly.

Vugu is a golang based experimentalframework.

TeaVM allows Java developers to writefrontend applications in Java and compile into Wasm.

Asm-Dom allows writingsingle page applications in C++ and it provides access to virtual dom.

Here is a list of languages and frameworks whichsupport WebAssembly.

https://github.com/appcypher/awesome-wasm-langs

Future of WebAssembly

Currently the WebAssembly community is workingon introducing a fantastic set of features, such as,

·        Threading

·        Exception handling

·        Garbage collectionand

·        ECMAScript moduleintegration.

For the updated set of features visit https://webassembly.org/docs/future-features/ .

What do you think about WebAssembly? Share youropinion as a comment.

References

·        https://webassembly.org/

·        https://www.w3.org/2019/12/pressrelease-wasm-rec.html.en

·        https://marcoselvatici.github.io/WASM_tutorial/

·        https://blog.sessionstack.com/how-javascript-works-a-comparison-with-webassembly-why-in-certain-cases-its-better-to-use-it-d80945172d79

·        https://medium.com/hackernoon/webassembly-the-journey-what-is-wasm-caf9871108aa