WASM: The Key to Next-Level Performance
Tags: webassembly, django, webdev, performance
Published: 2023-10-13 03:21:50

Regardless of the industry in IT you work in, be it IOT, web, mobile, etc., your user will always expect your apps to perform. Failure to which your app might get negative reviews if your app is unresponsive, crashes, or is slow. Learn how to improve performance using in Django using WASM.


In this article, you will learn about:

1. What is WASM and what are some of its goals and motivations?

2. What WASM features have contributed to an improvement in performance?

3. How can you optimize your apps for better performance with WASM?

4. Some use cases of WASM and how real-life apps have leveraged it to boost their performance.

## What is Performance?

Application performance is the measure of how responsive your application is to the end user. Performance is measured in terms of latency, CPU speed, memory usage, and average response time among many more.

To develop performant apps, you’ll always need to keep these two questions at the top of your mind:

1. How do you ensure your app consumes a finite amount of memory when in use?

2. How responsive is your app to the end users?
Both of these factors dictate how successful your app is and is a huge metric for investors and top-level management.

## What is WASM?

Web Assembly is a technology that was started as a way to use languages other than JavaScript in the browser. It achieves this by compiling native code written in languages such as C++, Rust, Django, etc. into binary code and embedding the code directly in the browser as you would with Javascript. WASM has led to increased performance, security, portability, and ability to re-use code across various platforms e.g. web, mobile, desktop, etc. 

Although it was initially started as a way to bring portability, security, and performance to the web, its use cases extend to mobile, cloud applications, IoT devices, serverless apps, legacy apps, and more. Every software developer will benefit greatly from learning what WASM has to offer.

## WASM and Performance Improvement

WASM is described to have near native performance and you can achieve lightning-fast performance by compiling your Django code to WASM. The following WASM features contribute to the high performance:

1. **Speed**
WASM is compiled into binary instruction format. Unlike Javascript which has to be parsed and compiled at runtime, WASM files are already compiled which significantly reduces its load and execution time.

2. **Size**
WASM is compiled into a binary instruction format that takes up less space. Due to the lightweight nature of WASM-compiled apps, the time taken to load them on the browser is also less compared to non-WASM apps. Lightweight apps also reduce the cold start time of apps since the resources being populated in the apps take a shorter time. 

3. **Reduced Latency**
Latency is the time it takes for the user to get a response back from the server. Some factors such as a cold start and slow server can contribute to increased latency. WASM is compiled into binary instruction format. Unlike Javascript which has to be parsed and compiled at runtime, WASM files are pre-compiled, reducing the app’s load and execution time. The lightweight nature of WASM apps also contributes to a reduction in the cold start time of Django apps since fewer resources are being populated in the apps and it also takes a shorter time to transmit them over the network.

4. **Linear Memory**
WASM uses linear memory to store values in a heap/stack. The binary code is stored in contiguous mutable arrays making the data easily accessible.
With WASM, you can deploy Django-WASM apps on the web and achieve native-code-level speed. Learn how you can improve the performance of your WASM apps below.


## Performance optimizations with WASM

Sooner or later, it will happen. Your application will start to get unusable either due to technical debt accrued or it being too large due to legacy code and you will have to learn how to optimize your app for better performance. Unfortunately, you can’t just execute your code using WASM and expect peak performance, you have to do some fine-tuning to achieve this. In this section, you’ll learn about some of the ways you can optimize your WASM code for lightning-fast performance.

1. **Concurrent and parallel processing**
Concurrency refers to the ability of an application to process more than one task at the same time while parallel processing involves executing two concurrent tasks at the same time on different CPU cores. WebAssembly now lets you run parts of your code in parallel using threads on different CPU cores of the users’ infrastructure which reduces the execution time. This overall reduction in execution time makes the apps run faster thus increasing performance.

2. **Multithreading**
Multithreading is the process of running multiple processes simultaneously using different processors during execution time. For example, you should use multithreading to run long-running background jobs such as image and video processing on separate worker threads. By using background jobs to run time-consuming tasks, the interactive UI remains usable since the user isn’t waiting for your app to load. Multithreading improves performance by reducing the processing time of your apps.

3. **Reduced Memory Usage**
Memory is the part of a computer where instructions and data are stored before it’s accessible by the program. Both the memory size and speed of your server will affect how performant your app is. WASM stores its code in contiguous mutable arrays making the data easily accessible. You should use SharedArrayBuffer, which lets several wasm modules share the same memory space, to leverage the shared memory functionality. This will ultimately lead to a reduction in the memory footprint of your Django-WASM apps consequently improving performance. 

4. **Lazy Loading**
Lazy loading is a technique used in programming to only load modules as the user needs/interacts with them. Lazy loading can improve the performance of your Django-WASM time by reducing the initial load time. When a WASM module needs to be loaded to the browser, it has to be parsed, built, and executed which can take some time. Only loading modules on a need basis will lead to the general performance improvement of your app. E.g an e-commerce app that loads high-resolution images can greatly benefit from this concept. Instead of loading the whole app, you only load the parts of the app that the user sees on the screen at that particular time. You can use paging or scroll view to load the other items on demand as the user scrolls.

5. **Garbage Collection**
Garbage collection is the process of de-allocating the parts of memory that are no longer being used by an application. WASM doesn’t naturally do garbage collection, so implementing this will reduce how much memory your app uses while running. Use libraries such as wasmtime to implement this.

## Using WebAssembly from Python
Compiling your Python code to WASM will require you to have a Python WebAssembly module that will be loaded to the WebAssembly runtime then you’ll point this towards the script you want to run.

In this section, you’ll create a simple Hello World app script using [wagi-python](https://github.com/fermyon/wagi-python). You will follow the steps below to get a fully functional app running in your browser:

1. Download [wagi-python](https://github.com/fermyon/wagi-python)

2. Navigate to your new project’s directory code/env.py and add the following code:
`print ("Hello WASM")`

3. Compile this code to wasm using the wasm-python command below:

```
wagi \ -e 'PYTHONHOME=/opt/wasi-python/lib/python3.11' \ -e 'PYTHONPATH=/opt/wasi-python/lib/python3.11' \ -c modules.toml
```

4. The app should be running on `http://127.0.0.1:3000`

## Conclusion

By utilizing WASM, from reduced time load, decreased latency, efficient memory usage among many more, you will tap into lightning fast performance in your applications. 
You can also compile Python code to wasm using [python-wasi](https://github.com/fermyon/wagi-python) to compile Python code.