WebAssembly vs. Javascript  

WebAssembly, the low-level assembly-esque language and compile target, arrived at cross-browser consensus earlier this year. It is now available in the latest Beta version of Samsung Internet (v7.2.10.12). Industry pundits are hailing the new code for its speed and ability to bring near-native performance to the web. And the question is now being asked, how much faster is it than JavaScript? How do the WebAssembly and JavaScript stacks compare? Will WebAssembly kill JavaScript? How will it affect the future of web development?

In this post, we’ll do a deep dive into WebAssembly, then look at a comparison between the two.

WebAssembly

WebAssembly (also known as WASM) is an efficient, low-level bytecode for the web. On the WebAssembly developer website, documentation describes it as “a new type of code that can be run in modern web browsers and provides new features and major gains in performance”.

You can use more than twenty different languages, including JavaScript, C, C++, Rust, Python and others to write your program then compile it to WebAssembly. This results in a web app that is fast to load and execute. WebAssembly was not built to be written by hand, but instead to be used as an effective compilation target for low-level source languages. The reason this translates to speed is that it offers a way to run code written in several languages on the web at near-native speed, with client apps running on the web that wouldn’t have been able to run previously.

You don’t have to have knowledge of how to create WebAssembly code to leverage it. WebAssembly modules can be imported into a web or Node.js app, which exposes the functions of WebAssembly for deployment via JavaScript. Rather than working as competition, JavaScript frameworks can use Web Assembly to its favor for performance advantages and new features.

WebAssembly is an open standard developed by a W3C Community Group.

Goals for WebAssembly

  • Speed – WebAssembly code can be executed at near-native speed: it runs at just 20% slower than native code execution
  • Portability – WebAssembly is browser-agnostic: it works across multiple platforms by leveraging common hardware capabilities and has similar execution times across them
  • Readable & debuggable – the fact it has a human-readable text format allows code to be written, viewed and debugged by hand
  • Security – It is built to run in a safe, sandboxed execution environment. It will enforce the browser’s policies on permissions and same-origin to ensure it has no security vulnerabilities
  • Maintains backward compatibility
  • Flexible – plays well with other technologies

WebAssembly overall has an efficient and portable representation:

    • Compact: WebAssembly has a binary format, which because it is smaller than typical text or native code formats, is faster to transmit
    • Modular: programs within WebAssembly can be split up into component parts, which can be transmitted, cached, and consumed separately
    • Efficient: in a single pass, code can be decoded, validated, and compiled with either just-in-time (JIT) or ahead-of-time (AOT) compilation
    • Streamable: decoding, validation, and compilation can begin as quickly as possible (even before all data has been viewed)
    • Parallelizable: decoding, validation, and compilation can be split into numerous independent parallel tasks
    • Portable: no architectural assumptions are made that are not broadly supported across modern hardware

The WebAssembly Web Platform

The Web platform essentially has two parts:

(i) a virtual machine (VM), which runs the code for the web app (both WebAssembly and JavaScript)

(ii) a series of web APIs, which the web app is able to call to control the functionality of the web browser/device to make things happen (DOM, CSSOM, WebGL, IndexedDB, etc.)

WebAssembly Java API

The WebAssembly JavaScript object is the namespace for all WebAssembly-related functionality. The main uses for the WebAssembly object are:

WebAssembly Consensus

WebAssembly Consensus was reached earlier this year by members representing four browsers, Chrome, Edge, Firefox, and WebKit. Consensus was reached that the design of the initial WebAssembly API and binary format is complete “to the extent that no further design work is possible without implementation experience and significant usage”. This also means that moving forward, future features will be designed to ensure backwards compatibility.

The WebAssembly consensus includes a JavaScript API and binary format accompanied by a reference interpreter.

Future steps the WebAssembly community group and contributors plan to take include:

  • distilling the design and spec interpreter repos into a single unified specification
  • suggest a new charter for a W3C WebAssembly Working Group
  • graduate the WebAssembly LLVM backend from experimental to stable (and update Emscripten)
  • prototype additional WebAssembly integration into browser developer tools
  • commence work on post-MVP features

Test Out WebAssembly

This open source project lets you play around with WebAssembly right now in your web browser: https://webassembly.studio/ It is built to run close to native speed.

WebAssembly and JavaScript

Which is faster?

While many call WebAssembly a gamechanger due to the fact that it can run code on the web faster, there have been mixed results in proving which code is faster.

Software developer KBall is a big fan of WebAssembly for speed reasons. He cites various studies, including Firefox’s demonstration that WASM in comparison to JavaScript can be compiled and executed as quickly as it comes over the wire.

Firefox proved that in terms of streaming compilation, the browser is able to compile the code as it is still being downloaded. In addition, the latest release of Firefox includes a 2-tiered compiler that compiles code 10-15 times more quickly than the optimizing compiler. Working in tandem, the two changes mean Firefox compiles code more quickly than it comes in from the network.

KBall also cites a set of benchmarks published by Figma, a browser-based design tool that compared implementations between asm.js vs. WebAssembly, which demonstrated a 3x improvement in load time enabled by WebAssembly. Figma found that for large docs, load time went from 10+ seconds to under 5.

KBall points out that run-time performance improvements “have been less dramatic”, but are “still in evidence”. For intense graphical operations, comparing WASM to D3 demonstrated a 30% improvement in large projects.

The Samsung Research America test – Winston Chen, Engineer ran a performance test to compare the speed of WebAssembly and JavaScript.

Chen’s experiment involved writing several implementations of matrix multiplication in JavaScript and C++. The first implementation (ijk) creates a baseline to compare to other implementations. The second (kji) is similar to the first, but deliberately misuses temporal locality. The third (bmm) leverages temporal locality. The second and third implementations focused on determining whether or not a well written function in JavaScript will outperform a poorly written function in C++.

Overall, Chen found that “the WebAssembly implementations outperform the JavaScript implementations by a significant amount on the bigger matrix sizes, which is what I expected. But in the graph of array sizes 64 to 256 shows that the JavaScript implementation actually out performs the Web Assembly implementation”.

Full details can be found here.

The Sqreen test – this was run to see how fast WASM modules can perform compared to JavaScript when handling simple numerical values, strings and arrays. Several times, JavaScript appeared to be the faster code. When it was investigated, Sqreen found “The raw execution of an algorithm in WASM is almost always faster than in JavaScript. However, the cost of writing data into the WASM module’s memory can be so high that it removes the benefit of using WASM in the first place.” On looking into this further, the researcher ran another experiment using a method with static parameters and looping 1,000 times around that. After which, the rust-based WASM alternative outran JavaScript. However, he continued to find that “the cost of writing complex data structures in WASM memory is pretty high” and “the longer the string, the slower the operation”.

Full details can be found here.

Pros to WebAssembly

  • Speed – WebAssembly is faster to load inside the browser than JavaScript as the already-compiled WASM files need to be transported over the Internet. WASM is a low-level assembly-esque language with a compact binary format. To load JavaScript, the browser needs to load all the ‘.js.’ files that are textual
  • Performance boosts – if you are only handling numeric data or your algorithm is highly complex and worth the cost of parsing arguments to the WebAssembly module
  • Flexibility – typically the virtual machine part of the web platform could only load JavaScript, which has worked well generally; however, more intensive use cases such as 3D games, VR and AR, image/video editing and computer vision demand native performance
  • Language – WebAssembly can be preferable if you don’t like the JavaScript language
  • Diversity of language – WASM supports over 20 different languages, including Rust, C/C++, Java, Python, Elixir, Go and C#/.Net – this enables a huge number of web frameworks for developers of these languages, meaning they can develop applications directly in their preferred language (this has already begun with Yew for Rust and Humble in Go)
  • Obfuscated code – WebAssembly is useful if you want to ship obfuscated code in browsers
  • Cost – downloading, parsing and compiling the large size of JavaScript applications can be costly, in particular on mobile and other resource-constrained platforms
  • Future development – WebAssembly intends to support languages with garbage-collected memory models down the road

Cons to WebAssembly

  • Time – writing a full web application in WebAssembly has been said to be slow, painful and counterproductive as there are no debuggers thus a lot of time will need to be spent on handling trivial topics.
  • Sqreen says writing a full web app in WebAssembly is counterproductive because “your framework will expose DOM-related methods and these calls will be pretty slow”.

Pros to JavaScript

  • JavaScript is flexible and expressive for writing web applications
  • It is dynamically typed
  • No compile step is required
  • It has a massive ecosystem, which offers powerful frameworks, libraries and other such tools

How do WebAssembly and JavaScript work together?

  • The virtual machine in the web platform can load and run both types of code.
  • The two code types can call one another if required
  • The WebAssembly JavaScript API wraps exported WebAssembly Code with the normal functions of JavaScript
  • WebAssembly’s code can import and synchronously call normal JavaScript functions
  • WebAssembly modules are symmetric in lots of ways to ES2015 modules

Conclusion

With the rise of WebAssembly, front-end development is underway a significant change. It is hard to see how exactly the change will play out, however, it is clear that the future of web development will be fast, parallel and linguistically diverse.

Tests of speed and load times have born out impressive results for WebAssembly. And even if significant numbers of web applications continue to be in JavaScript due to its mainstream status and other unique advantages, WebAssembly libraries and frameworks will help developers take advantage of the speed boosts gained from WebAssembly while mainly developing in JavaScript.

Parallelism is not yet fully realized in WebAssembly, but compared to JavaScript which was designed as a single-threaded language, it shows some capability already and much future promise. The threads feature in WebAssembly is still currently a proposal, but once it becomes a reality we will likely see many web applications leveraging fine-grained parallelism. This will mostly likely occur at the level of frameworks and libraries where there is tremendous potential.

It’s worth keeping an eye on how WebAssembly continues to perform against (and with) JavaScript as the tooling continues to advance and more browsers, tools and libraries take advantage of its performance capabilities.

Digiprove sealCopyright secured by Digiprove © 2018