What Is WebAssembly?
WebAssembly is a different type of code that can be sent to the browser. It’s in bytecode, format meaning that it’s shipped in low-level assembly language by the time it reaches the browser. The bytecode is not meant to be written by hand, but can be compiled from any programming language such as C++ or Rust. The browser can then take any WebAssembly code, load it as native code, and achieve high performance.
The WebAssembly tooling often consists of a C++ compiler. There are many tools in current development, but one that has reached maturity is Emscripten. This tool compiles C++ code into a WebAssembly module and builds standards-compliant modules that can run anywhere. The compiled output will have a WASM file extension to indicate that it’s a WebAssembly module.
One advantage in WebAssembly is that you have all the same HTTP caching headers when you fetch modules. Plus, you can cache WASM modules using IndexedDB, or you can cache modules using session storage. The caching strategy revolves around caching fetch API requests and avoiding yet another request by keeping a local copy. Since WebAssembly modules are in bytecode format, you can treat the module as a byte array and store it locally.
Now that we know what WebAssembly is, what are some of its limitations?
Code that runs in a browser, runs in a sandboxed environment and doesn’t have access to the file system. You may create an in-memory virtual file system instead that comes preloaded with data.
The application’s main loop uses co-operative multitasking, and each event has a turn to execute. An event on the web often comes from a mouse click, finger tap, or a drag and drop operation. The event must return control to the browser so that other events can be processed. It’s wise to avoid hijacking the main event loop, as this can turn into a debugging nightmare. DOM events are often tied to UI updates, which are expensive. And this brings us to another limitation.
In WebAssembly, some good advice is to stick to what can perform very fast. Use the tool for the job that yields the most performance gains while avoiding pitfalls. Think of WebAssembly as this super-high-speed system that runs well in isolation without any blockers.
Can I Use wasm? Data on support for the wasm feature across the major browsers from caniuse.com.
The post WebAssembly: Solving Performance Problems on the Web appeared first on SitePoint.