The original link: blog.logrocket.com/webassembly…

How do you run native code in the browser, why do we do it, and what does it mean for the future of JavaScript and the Web

No matter which browser – Chrome, Firefox, Edge or Safari. The code is always parsed and executed by the browser’s JavaScript engine, which only runs JavaScript code. Unfortunately, JavaScript doesn’t always run as efficiently as we’d like. That’s why WebAssembly exists.

WebAssembly is a new type of code that runs in modern browsers. The goal is to improve web performance. Because it is binary data the data is not very large and therefore can be loaded and executed quickly. We don’t need to write WebAssembly, we can get it by writing other high-level languages.

Assembly usually refers to human-readable language similar to machine code. Machine code is a set of data that can be understood by the processor.

Assembly languages and machine code

Each high-level language is translated and converted into machine code and then run on the processor. Different processor structures require different types of machine code and different assembly languages.

Compiling source code for different processor architectures

WebAssembly is not an assembly language because it is not implemented for a specific machine. It is used in the browser, and we can execute the code in the browser. We don’t have to worry about which machine our code will run on.

WebAssembly as an intermediary compiler target

WebAssembly is a language for conceptual machines that can run on mainstream machines. When the browser downloads WebAssembly code, the browser quickly converts it to machine code.

The figure below shows WebAssembly in action. It has an easy-to-read text format *(.wat)*, but the binary representation is what you actually deliver to the browser (.wasm).

WebAssembly textual and binary format

What WebAssembly enables you to do is compile things like C, C++, or Rust code into so-called WebAssembly modules. You can load it into your Web application and call it from JavaScript.

It’s not a JavaScript replacement, it works with JavaScript.

WebAssembly module in an application

Why do we need WebAssembly

Think of a time when you need to use software outside of your browser: video games, video editing, 3D rendering, or music production. These applications are computationally intensive and require high performance. This kind of performance is hard to get from JavaScript.

JavaScript began as a simple scripting language designed to bring some interactivity to a web full of lightweight hypertext documents. It was designed to be easy to learn and write, but it wasn’t designed to be efficient. Over the years, browsers have added optimizations to the way JavaScript parses, leading to significant performance improvements.

With the rapid development of JavaScript, you can perform more operations in the browser. New apis bring interactive graphics, video streaming, offline browsing, and more. In turn, more and more rich applications (previously native only) are starting to appear on the Web. Today, you can easily edit documents and send emails from your browser, but JavaScript performance is still difficult in some areas.

Video games are particularly challenging because they not only have to coordinate audio and video, but often physical and artificial intelligence as well. Being able to run games efficiently on the web will open the door to bringing [many other applications](WebAssembly: How and Why) to the web, which is what WebAssembly is all about.

Why is the Web so appealing

The beauty of the Web is that it’s like magic — it can be used anywhere. ** No download, no installation required. ** With one click, the Web application will be delivered as soon as you need it. More secure than downloading and running binaries directly on your computer. Because browsers already have security policies in place to prevent code running in them from interfering with your system. Sharing on the network is simple – links are just clickable strings that you can place anywhere.

It is the only truly universal platform that can be accessed by your applications on any device. This also allows you to maintain a single code base, making updates easy and ensuring that every user has access to your application.

Because of these built-in features and the interactivity that the web provides, we’ve gone from hypertext and small scripting languages to a very powerful and popular platform full of amazing applications and features. But until now, it was still fundamentally powered by the same scripting language that was never really designed to do it all in the first place.

What does WebAssembly bring

This is what makes WebAssembly so special and so well suited to the Web:

  • efficient
  • portable
  • flexible

WebAssembly is designed to be efficient. Its binaries are much smaller than text JavaScript files. Because of their size, they download faster, which is especially important on slow networks.

They also decode and execute faster. JavaScript is a dynamically typed language, and variable types do not need to be defined or compiled beforehand. This makes it easy and fast to write, but it also means the JavaScript engine has a lot of work to do. As code executes on the page, it must parse, compile, and optimize the code.

Parsing JavaScript involves converting plain text into a data structure called an Abstract syntax tree (AST) and converting it to binary format. WebAssembly is provided in binary format for faster decoding. It is statically typed, so unlike JavaScript, the engine does not have to speculate at compile time about which types will be used. Most optimizations occur during source code compilation, even before it enters the browser. Memory is managed manually, as it is in languages like C and C++, so there is no garbage collection. All of these provide better, more reliable performance. The execution time of the WASM binary is only 20% slower than that of the same native code.

Relative time spent processing WebAssembly in JavaScript engine

One of the main goals of designing WebAssembly is portability. To run an application on a device, it must be compatible with the device’s processor architecture and operating system. This means compiling source code for every combination of operating system and CPU architecture that you want to support. With WebAssembly, there is only one compile step, and your application will run in every modern browser.

Compiling native code to run on different platforms vs. compiling to WebAssembly

Not only can you port your own applications to the Web, you can also port a large number of existing C++ libraries and open source applications to the Web. It is a language that is supported on almost every platform, including iOS and Android. With WebAssembly, it can be used as a common language for deployment across the Web and mobile.

The most exciting thing about WebAssembly is that it brings more flexibility to Web authoring. Until now, JavaScript has been the only fully supported language in Web browsers. With WebAssembly, Web developers will be able to choose other languages, and more developers will be able to write code for the Web. JavaScript is still the best choice for most use cases, but now you have the option of occasionally using a specialized language when you really need to improve. Parts like UI and application logic can use JavaScript, and the core functionality is in WebAssembly. When optimizing the performance of an existing JS application, you can rewrite the bottleneck in a language better suited to the problem.

Currently fully supported languages are C, C++, and Rust, but many others are in development, including Kotlin and.NET, both of which already provide experimental support.

works

You need a tool to compile the source code into WebAssembly. One way is to use LLVM, an experienced modular compiler toolchain that can be set up to use different languages. To compile C and C++, you can use Emscripten, a simpler llVM-based tool. Rust Nightly has its own compiler, RUSTC, and can output WebAssembly directly.

If you have a “Hello world” written in C, this Emscripten command will generate the files needed to run it in the browser. What you get is a WebAssembly module with HTML and JS files.

emcc hello.c -s WASM=1 -o hello.html
Copy the code

Compiling C/C++ code to WebAssembly with Emscripten

You need HTML and JS files because WebAssembly doesn’t have direct access to any platform API — DOM, WebGL, WebAudio, etc. To use any of these, or even to display the output of the WebAssembly code on the page, you must use JavaScript. Emscripten creates JS code to set up your modules and make it possible to communicate with Web apis. The HTML file loads the JS and displays the WebAssembly output in a Textarea or canvas element.

You can think of WebAssembly binaries as regular application modules: browsers get them, load them, and execute them. They have import and export capabilities, allowing you to work with them like JavaScript objects. You can call WebAssembly functions in JavaScript code or JavaScript functions in WebAssembly modules.

It has only four basic types, all of which are numbers — integers and floating point numbers (i32, i64, F32, and F64). This means that passing more complex data types between JavaScript and WebAssembly is not easy. For example, if you want to pass a string, you must encode it as an array of numbers and then pass a pointer to it. It can only read and write from its own linear memory and cannot directly access external JavaScript variables unless they are copied into memory or passed through the call stack.

It’s not very quick to make a lot of calls through JavaScript these days, because the engine has to do some setup work every time. This may change in the future, but for now the good advice is to treat WebAssembly as a stand-alone system and use it to unload a lot of work.

If you want to try it out without any setup, go to WebAssembly. Studio or WebAssembly Explorer.

Use?

Of course!

It’s here, and it’s real. WebAssembly supported all major browsers last year. It currently supports 74.93% of users worldwide and even 82.92% of desktop users. As a fallback to older browsers, you can use Emscripten to compile to asM.js — a subset of JavaScript that only uses numbers (no strings, objects, and so on). It is a format that led directly to the creation of WebAssembly and is widely used on the web, for example for image compression when uploading photos to Facebook and image editing in Adobe Lightroom.

Browsers that support WebAssembly

There are already some very exciting examples of WebAssembly in the real world.

I mentioned that video games are an important target for WebAssembly and that Unity and Unreal Engine 4 have already been shown working. You can play tank games! WebAssembly runs in the Unity engine and Epic has a short WebAssembly live demo.

webassembly.org/demo/

Figma is an interface design tool that runs in a browser, allowing designers to easily collaborate and share their work. It is written primarily in C++ and has a 2D WebGL rendering engine that can handle very large documents. Initially, they compiled C++ code for the Web using asm.js. By switching to WebAssembly, the load time of documents, regardless of their size, increased by more than three times.

AutoCAD is a design software, mainly used in a variety of engineering fields, for drawing plans, circuits, pipe design and other drawings. It’s written in C++ and has been around for 35 years, longer than the web itself. Thanks to WebAssembly, it can now be used as a Web application without having to rewrite such a large code base in another language.

You can expect more and more applications to use WebAssembly, and there are some interesting demonstrations online, such as video editors, ray trackers, and facial recognition algorithms running in browsers.

In the future?

Browsers are already working on new features. Upcoming support for threading and garbage collection will make WebAssembly a better target for compiling languages like Java, C#, and Go. One of the important goals is to create debugging tools that support source mapping, which will allow developers to easily map WebAssembly to their source code.

**JavaScript will still have a place in Web development. ** It’s a great language, flexible enough to build almost anything, and the gaps it doesn’t handle well can now be filled with WebAssembly. It’s impossible to compile JavaScript into WebAssembly, and it really doesn’t make much sense, since browsers are designed to use JS directly and maximize its performance.

But even if you continue to use only JavaScript, you can still benefit from WebAssembly and the speed increase it brings with improved libraries and frameworks. Soon, you’ll be able to implement it as you use WebAssembly, and it’s possible to implement some React functionality in WebAssembly as well.

The future is possible!