The Detroit Post
Saturday, 16 October, 2021

Rust For Javascript

Carole Stephens
• Tuesday, 29 December, 2020
• 10 min read

Companies like Figma and Discord are now leading the way by also using Rust in their client applications. Finally, I’ll present a quick performance evaluation of my COVID-19 simulator web app that uses Rust and JavaScript.

javascript rust hello rs


Admittedly, it takes time to get used to this syntax, with the pipe (|) replacing the parentheses. But after overcoming the initial awkwardness, I find it clearer to read than another set of parentheses.

The main difference is that in Rust we have to specify the type (Point). String literals are encoded in Unicode, handling special characters without issues.

I could go on with the list, but I think my point is clear by now: Rust has a rich set of features that are also used in modern JavaScript. Luckily, Cargo takes care of invoking the compiler for us.

And with webpack, we’ll be able to also hide cargo behind NPM run build. With this guide, the normal workflow of a web developer can be retained, once Rust is set up for the project.

Rust has been built from the ground up in recent years, taking into account everything humanity has learned about programming-language design in the past few decades. Pattern matching in Rust is a pet feature of mine.

rust javascript

Other languages have switch and case to avoid long chains like this: I think that’s pretty neat, and I hope JavaScript developers can also appreciate this syntax extension.

To say it straight, using a strict type system can feel very cumbersome at times. If you thought the type systems of C++ or Java are strict, then brace yourself for a rough journey with Rust.

But I understand that for beginners, it can be very annoying to fight the compiler all the time. It will install the compiler (rust) and the package manager (Cargo) for the newest stable version of Rust.

Check the installation by typing cargo --version in a terminal. We start with a Rust project that can be compiled into a NPM package.

These are dependencies from crates.Io, the default package repository that Cargo uses. Our final binary will only contain the Web API bindings selected like this.

rust javascript

The use statements at the top are for importing items from other modules. The pub modifier is short for “public” and acts like export in JavaScript.

The annotation # is specific to Rust compilation to Web Assembly (Was). We need it here to ensure the compiler exposes a wrapper function to JavaScript.

This is because JavaScript allows a variable number of parameters, while Rust doesn’t. A full list of functions that can be called on the console from within Rust is available in the Weiss documentation.

When it expects a reference to a Value as an argument to a function, it won’t accept a static string. The Rust compiler is smart enough to defer which types are involved in the conversion, since the function signature leaves only one possibility.

In this case, it will convert to Value, which is a wrapper type for a value managed by JavaScript. Then, we also have to add the & to pass it by reference rather than by value, or the compiler will complain again.

javascript rust

I’d suggest you use the exact same versions when following this Rust tutorial. This is a webpack plugin specifically for loading Rust packages built with wasm-pack.

Feel free to adjust these if you prefer a different setup. But now that all’s in place, we can easily extend the Rust code without worrying about any of this.

Upon saving changes to, you should automatically see a recompilation and a live update in the browser, just like with JavaScript ! It can only run in the browser through Was and this limits its usefulness quite a bit.

Even though you could replace virtually all JavaScript code with Rust if you really wanted to, that’s a bad idea and not what Was has been created for. For example, Rust isn’t a good fit for interacting with the UI of your website.

I think of Rust + Was mas an additional option that can be used to run a CPU-heavy workload more efficiently. For the price of larger download sizes, Was avoids the parsing and compilation overhead that JavaScript code faces.

rust javascript

A red square represents a cell infected with the virus. By clicking on individual cells, you can add or remove infections.

After a fixed number of days of being infected, the cell recovers and is immune for the rest of the simulation. The form on the top right side controls the various simulation parameters.

Only when clicking on Next Day or Start Simulation will the Rust code be invoked to calculate all infections. I also implemented an equivalent interface in JavaScript, so that we can easily do a performance comparison later.

Even when running the automated simulation, this takes effect immediately (for the next day). The simulation object (implemented in Rust and JavaScript) exposes only one class with a constructor and two additional methods.

Defining the struct Simulation as above with the # annotation will generate a JavaScript wrapper class that can be used as a proxy. To define methods on the struct, we use an imply block in Rust.


The biggest difference to JavaScript is that all types are explicitly mentioned on the function signatures. In the function next_day(), the two parameters input: &, output: smut each expect a slice of u8, which is essentially an array.

If the method changes the internal state of the object, it must be signified by explicitly adding smut self in the parameter list. For the return type of function, Rust uses the arrow notation ().

Rust will assign unique numbers to the values, and we, the programmers, need not worry about it. The two dots between the two values create a range of integers that the for loop iterates over.

Peeking inside the loop body, it starts with a lookup in the input array: It reads the corresponding u8 from the input array and converts it to an InfectionStatus according to the constants defined in JavaScript.

Thus, the current variable is of type InfectionStatus, and we can use Rust ’s powerful pattern matching on it: If the cell is healthy now, we compute the chance to get infected today in a separate function that will loop over all neighbors in the configured radius.

rust facepunch community pc month update devil

First, whether the cell dies today, again based on a random number generated on the spot. Otherwise, we check if the recovery date has been reached, in which case the new status will be Immune .

Finally, if none of the two checks were positive, then the infection day counter is increased by one. The last option in the pattern matching is that the cell is already dead or immune.

After the match expression, we call the setter function that takes an InfectionStatus value. It converts the value back to an u8 and writes it to the output array.

I won’t go into the implementation details of that here, but I encourage you to have a look at the source code if you’re curious. To answer that, I picked a couple of settings and compared the speed of the Rust implementation to the one in JavaScript.

With the default settings (100 cells, infection radius = 2) the first simulation day takes 0.11ms on average with Rust and 0.72ms with JavaScript. Below are charts from experiments with more cells and an altered radius, which increases the total workload.

netflix apatow judd teaser relationships trailer take season tv

The chart shows that Rust is significantly faster than JavaScript on the first simulation day, no matter the setting. The Rust version keeps a comparatively stable execution time across all days.

The whole workload is one huge loop doing the same computation over and over again with only slightly changing values. To investigate a bit further, I performed the same tests on my Samsung Galaxy S7.

Starting from day four, both the 3000 and the 10000 nodes experiment reached a relatively stable performance for JavaScript. Was can be much faster in the right circumstance and it is generally more consistent than its JavaScript counterpart.

You would want measure how long the Rust code takes to execute, including the call-overhead from JavaScript. The version deployed in the Code Pen demo also linked earlier still contains the benchmarking code.

You can just open the developer console to read the times you get on your device. Was support for Rust has now reached decent maturity, so it’s ready to start using it for your work.

rust obsolete rendered fail client

To quantify the performance of Rust, I implemented the full app also in JavaScript and did some benchmarks. The main takeaway is that only benchmarking can tell for sure which language is faster for your app.

Other Articles You Might Be Interested In

01: Drew Real Estate San Antonio
02: Drive For Amazon Austin
03: Drive For Amazon Houston
04: Drive For Amazon Indianapolis
05: Drive For Amazon Phoenix
06: Drone For Real Estate Video
07: Eagle Nest Real Estate Jersey City
08: Earley Real Estate Columbus Ne
09: Easter Restaurants Jacksonville Fl
10: Eastmore Real Estate Milwaukee Wi
1 -
2 -
3 -
4 -
5 -
6 -