asm.js is a
subset
In mathematics, a Set (mathematics), set ''A'' is a subset of a set ''B'' if all Element (mathematics), elements of ''A'' are also elements of ''B''; ''B'' is then a superset of ''A''. It is possible for ''A'' and ''B'' to be equal; if they a ...
of
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
designed to allow
computer software
Software consists of computer programs that instruct the Execution (computing), execution of a computer. Software also includes design documents and specifications.
The history of software is closely tied to the development of digital comput ...
written in languages such as
C to be run as
web application
A web application (or web app) is application software that is created with web technologies and runs via a web browser. Web applications emerged during the late 1990s and allowed for the server to dynamically build a response to the request, ...
s while maintaining performance characteristics considerably better than standard
JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
, which is the typical language used for such applications.
asm.js consists of a
strict subset
In mathematics, a set ''A'' is a subset of a set ''B'' if all elements of ''A'' are also elements of ''B''; ''B'' is then a superset of ''A''. It is possible for ''A'' and ''B'' to be equal; if they are unequal, then ''A'' is a proper subset ...
of JavaScript, to which code written in
statically typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a ''type'' (for example, integer, floating point, string) to every '' term'' (a word, phrase, or other set of symbols). Usu ...
languages with manual memory management (such as C) is translated by a
source-to-source compiler
A source-to-source translator, source-to-source compiler (S2S compiler), transcompiler, or transpiler is a type of translator that takes the source code of a program written in a programming language as its input and produces an equivalent so ...
such as
Emscripten
Emscripten is an LLVM/Clang-based compiler that compiles C and C++ source code to WebAssembly, primarily for execution in web browsers.
Emscripten allows applications and libraries written in C or C++ to be compiled ahead of time and run effi ...
(based on
LLVM
LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
).
Performance is improved by limiting language features to those amenable to
ahead-of-time optimization and other performance improvements.
Mozilla Firefox
Mozilla Firefox, or simply Firefox, is a free and open-source web browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation. It uses the Gecko rendering engine to display web pages, which implements curren ...
was the first web browser to implement asm.js-specific optimizations, starting with version 22.
asm.js is superseded by
WebAssembly
WebAssembly (Wasm) defines a portable binary-code format and a corresponding text format for executable programs as well as software interfaces for facilitating communication between such programs and their host environment.
The main goal of ...
.
Design
asm.js enables significant performance improvements for
web application
A web application (or web app) is application software that is created with web technologies and runs via a web browser. Web applications emerged during the late 1990s and allowed for the server to dynamically build a response to the request, ...
s, but does not aim to improve the performance of hand-written JavaScript code, nor does it enable anything other than enhanced performance.
It is intended to have performance characteristics closer to that of native code than standard JavaScript by limiting language features to those amenable to
ahead-of-time optimization and other performance improvements. By using a subset of JavaScript, asm.js is largely supported by all major
web browser
A web browser, often shortened to browser, is an application for accessing websites. When a user requests a web page from a particular website, the browser retrieves its files from a web server and then displays the page on the user's scr ...
s, unlike alternative approaches such as
Google Native Client
Google Native Client (NaCl) is a discontinued sandboxing technology for running either a subset of Intel x86, ARM, or MIPS native code, or a portable executable, in a sandbox. It allows safely running native code from a web browser, independ ...
.
Code generation
asm.js is not typically written directly: instead, as an intermediate language, it is generated through the use of a
compiler
In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
that takes source code in a language such as
C++ and outputs asm.js.
For example, given the following C code:
int f(int i)
Emscripten would output the following JS code:
function f(i)
Note the addition of
, 0
and the lack of type specifiers. In JavaScript, bitwise operators convert their operands to 32-bit signed integers and give integer results. This means that a
bitwise OR
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic opera ...
with zero converts a value to an integer (a very simple "conceptual" presentation of bitwise operators may not deal with type conversion at all, but every programming language defines operators for its own convenience, as Javascript does here). By doing this for each parameter, this ensures that if the function is called from outside code, the value will be converted to the correct type. This is also used on the return value, in this case to ensure that the result of adding 1 to i will be an integer (as otherwise it could become too large), and to mark the return type of the function. These conversions are required by asm.js, so that an optimising compiler can produce highly efficient native code ahead-of-time. In such an optimising compiler, no conversions are performed when asm.js code calls other asm.js code, as the required type specifiers mean it is guaranteed that values will already have the correct type. Furthermore, rather than performing a floating-point addition and converting to an integer, it can simply do a native integer operation. Together, this leads to significant performance benefits.
Here is another example to calculate the length of a string:
size_t strlen(char *ptr)
This would result in the following asm.js code:
function strlen(ptr)
In the generated code, the variable MEM8 is actually a byte-by-byte "view" of a typed buffer, which serves as the "heap" of the asm.js code.
Performance
Since asm.js runs in a browser, the performance heavily depends on both the browser and hardware. Preliminary benchmarks of C programs compiled to asm.js are usually within a factor of 2 slower than native compilation with
Clang
Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
.
Much of this performance gain over normal JavaScript is due to 100%
type
Type may refer to:
Science and technology Computing
* Typing, producing text via a keyboard, typewriter, etc.
* Data type, collection of values used for computations.
* File type
* TYPE (DOS command), a command to display contents of a file.
* ...
consistency and virtually no
garbage collection
Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of treatment or landfill. Waste collection also includes the curbside collection of recyclable ...
(memory is manually managed in a large typed array). This simpler model with no dynamic behavior, no memory allocation or deallocation, just a narrow set of well-defined integer and floating point operations enables much greater performance and potential for
optimization
Mathematical optimization (alternatively spelled ''optimisation'') or mathematical programming is the selection of a best element, with regard to some criteria, from some set of available alternatives. It is generally divided into two subfiel ...
.
Mozilla's benchmark from December 2013 showed significant improvements: "Firefox with
float32 optimizations can run all those benchmarks at around 1.5× slower than native, or better."
Mozilla points out that the performance of natively compiled code is not a single measure but rather a range, with different native compilers (in this case
Clang
Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
and
GCC) delivering code of differing performance. "In fact, on some benchmarks, like
Box2D,
FASTA
FASTA is a DNA and protein sequence alignment software package first described by David J. Lipman and William R. Pearson in 1985. Its legacy is the FASTA format which is now ubiquitous in bioinformatics.
History
The original FASTA program ...
and copy, asm.js is as close or closer to Clang than Clang is to GCC. In one case, asm.js even beats Clang by a slight amount on Box2D."
Implementations
The
Emscripten
Emscripten is an LLVM/Clang-based compiler that compiles C and C++ source code to WebAssembly, primarily for execution in web browsers.
Emscripten allows applications and libraries written in C or C++ to be compiled ahead of time and run effi ...
project provides tools that can be used to compile C and C++ codebases (or any other languages that can be converted to
LLVM
LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
IR) into asm.js.
All browsers with support for
ECMAScript 6
ECMAScript is a JavaScript standard developed by Ecma International. Since 2015, major versions have been published every June.
ECMAScript 2024, the 15th and current version, was released in June 2024.
Versions
In June 2004, Ecma International ...
should be able to run asm.js code, as it is a subset of that specification. However, since features were added in that edition to enable full asm.js support (), older browsers lacking those features may encounter problems.
Some browser implementations are especially optimised for asm.js:
*
Mozilla Firefox
Mozilla Firefox, or simply Firefox, is a free and open-source web browser developed by the Mozilla Foundation and its subsidiary, the Mozilla Corporation. It uses the Gecko rendering engine to display web pages, which implements curren ...
was the first web browser to implement asm.js-specific optimizations, starting with Firefox 22.
OdinMonkey, Mozilla's asm.js ahead-of-time compiler used in Firefox, is a component of
IonMonkey, the JIT compiler of
SpiderMonkey
SpiderMonkey is an open-source JavaScript and WebAssembly engine by the Mozilla Foundation. The engine powers the Firefox Web browser and has used multiple generations of JavaScript just-in-time (JIT) compilers, including TraceMonkey, Jäg ...
.
* Microsoft was implementing support for asm.js in
Chakra
A chakra (; ; ) is one of the various focal points used in a variety of ancient meditation practices, collectively denominated as Tantra, part of the inner traditions of Hinduism and Buddhism.
The concept of the chakra arose in Hinduism. B ...
, the JavaScript engine used by
Microsoft Edge Legacy
Microsoft Edge Legacy (often shortened to Edge Legacy), originally released as simply Microsoft Edge or Edge is a discontinued Proprietary Software, proprietary cross-platform software, cross-platform web browser created by Microsoft. Released ...
, performing validation to produce highly optimised JIT code.
* The optimizations of
Google Chrome
Google Chrome is a web browser developed by Google. It was first released in 2008 for Microsoft Windows, built with free software components from Apple WebKit and Mozilla Firefox. Versions were later released for Linux, macOS, iOS, iPadOS, an ...
's
V8 JavaScript engine in Chrome 28 made asm.js benchmarks more than twice as fast as prior versions of Chrome,
although Chrome's V8 does not use ahead-of-time compilation.
Adoption
Almost all of the current applications based on asm.js are C/C++ applications compiled to asm.js using
Emscripten
Emscripten is an LLVM/Clang-based compiler that compiles C and C++ source code to WebAssembly, primarily for execution in web browsers.
Emscripten allows applications and libraries written in C or C++ to be compiled ahead of time and run effi ...
or Mandreel. With that in mind, the kind of applications that are going to target asm.js in the near future are those that will benefit from the portability of running in a browser but which have a level of complexity for which a direct port to JavaScript would be infeasible.
So far, a number of
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s,
application framework
In computer programming, an application framework consists of a software framework used by software developers to implement the standard structure of application software.
Application frameworks became popular with the rise of graphical user inte ...
s,
programs,
libraries
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
,
games
A game is a Structure, structured type of play (activity), play usually undertaken for entertainment or fun, and sometimes used as an Educational game, educational tool. Many games are also considered to be Work (human activity), work (such as p ...
,
game engine
A game engine is a software framework primarily designed for the development of video games which generally includes relevant libraries and support programs such as a level editor. The "engine" terminology is akin to the term " software engine" u ...
s and other software have already been
ported. Some of them are given below.
Programming languages
*
C/C++:
Clang
Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
and
LLVM
LLVM, also called LLVM Core, is a target-independent optimizer and code generator. It can be used to develop a Compiler#Front end, frontend for any programming language and a Compiler#Back end, backend for any instruction set architecture. LLVM i ...
*
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
: targets
Emscripten
Emscripten is an LLVM/Clang-based compiler that compiles C and C++ source code to WebAssembly, primarily for execution in web browsers.
Emscripten allows applications and libraries written in C or C++ to be compiled ahead of time and run effi ...
*
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
: port of (micro)perl-5.16.3
*
Python – port of
CPython
CPython is the reference implementation of the Python programming language. Written in C and Python, CPython is the default and most widely used implementation of the Python language.
CPython can be defined as both an interpreter and a comp ...
*
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
– port of Ruby
Application frameworks
* pepper.js: Ports of miscellaneous
PNaCl apps (earth, voronoi, bullet, etc.)
*
Qt: ports of various Qt demos, plus KDE apps, such as
Kate Kate may refer to:
People and fictional characters
* Kate (given name), a list of people and fictional characters with the given name or nickname
* Gyula Káté (born 1982), Hungarian amateur boxer
* Lauren Kate (born 1981), American author o ...
Programs and libraries
*
OpenGL
OpenGL (Open Graphics Library) is a Language-independent specification, cross-language, cross-platform application programming interface (API) for rendering 2D computer graphics, 2D and 3D computer graphics, 3D vector graphics. The API is typic ...
,
SDL, and
SDL2
*
Vim (Vi IMproved)
*
FreeType:
TrueType
TrueType is an Computer font#Outline fonts, outline font standardization, standard developed by Apple Inc., Apple in the late 1980s as a competitor to Adobe Inc., Adobe's PostScript fonts#Type 1, Type 1 fonts used in PostScript. It has become the ...
font rendering in JavaScript, using FreeType
*
SQLite
SQLite ( "S-Q-L-ite", "sequel-ite") is a free and open-source relational database engine written in the C programming language. It is not a standalone app; rather, it is a library that software developers embed in their apps. As such, it ...
*
GNU Privacy Guard
GNU Privacy Guard (GnuPG or GPG) is a free-software replacement for Symantec's cryptographic software suite PGP. The software is compliant with the now obsoleted , the IETF standards-track specification of OpenPGP. Modern versions of PGP are ...
*
ctags
*
gnuplot
*
Graphviz
Graphviz (short for ''Graph Visualization Software'') is a package of open-source software, open-source tools initiated by AT&T Labs, AT&T Labs Research for Graph drawing, drawing graph (discrete mathematics), graphs (as in Vertex (graph theory ...
*
zlib
zlib ( or "zeta-lib", ) is a software library used for data compression as well as a data format. zlib was written by Jean-loup Gailly and Mark Adler and is an abstraction of the DEFLATE compression algorithm used in their gzip file compre ...
Game engines
*
Unreal Engine 3
Unreal Engine 3 (UE3) is the third version of Unreal Engine developed by Epic Games. Unreal Engine 3 was one of the first game engines to support multithreading. It used DirectX 9 as its baseline graphics API, simplifying its rendering code. The ...
: was ported in 4 days
*
Unreal Engine 4
Unreal Engine 4 (UE4) is the fourth version of Unreal Engine developed by Epic Games. UE4 began development in 2003 and was released in March 2014, with the first game using UE4 being released in April 2014. UE4 introduced support for Physically ...
*
Unity
*
ScummVM
Script Creation Utility for Maniac Mansion Virtual Machine (ScummVM) is a set of game engine recreations. Originally designed to play LucasArts adventure games that use the SCUMM system, it also supports a variety of non-SCUMM games by companies l ...
, which supports numerous classic adventure games
*
Godot
Games
* ''
Doom'': the open source
Freedoom game assets running on
PrBoom, which is based on the open source Doom code
* ''
SuperTux''
* ''
Dune II'' via OpenDune
* ''
BananaBread'' based on
Cube 2
* Every game in the
Humble Mozilla Bundle (''
Super Hexagon'', ''
AaAaAA! for the Awesome'', ''
Osmos'', ''
Zen Bound 2'', ''
Dustforce DX'', ''
Voxatron'', ''
FTL: Advanced Edition'' and ''
Democracy 3'')
Emulators
* EM-DOSBox: an Emscripten port of
DOSBox
DOSBox is a free and open-source MS-DOS emulator. It supports running programs primarily video games that are otherwise inaccessible since hardware for running a compatible disk operating system (DOS) is obsolete and generally unavailab ...
*
Start9.io: a web emulation platform targeting multiple gaming architectures
* JSMESS: a port of the
MESS
The mess (also called a mess deck aboard ships) is a designated area where military personnel socialize, eat and (in some cases) live. The term is also used to indicate the groups of military personnel who belong to separate messes, such as the o ...
emulator for many game consoles and computer systems
Mathematics
* HTML5 Fractal Playground – draws iterating-function generated
fractal
In mathematics, a fractal is a Shape, geometric shape containing detailed structure at arbitrarily small scales, usually having a fractal dimension strictly exceeding the topological dimension. Many fractals appear similar at various scale ...
s, such as the
Mandelbrot set
The Mandelbrot set () is a two-dimensional set (mathematics), set that is defined in the complex plane as the complex numbers c for which the function f_c(z)=z^2+c does not Stability theory, diverge to infinity when Iteration, iterated starting ...
.
Deprecation
asm.js is mostly rendered obsolete with the introduction of
WebAssembly
WebAssembly (Wasm) defines a portable binary-code format and a corresponding text format for executable programs as well as software interfaces for facilitating communication between such programs and their host environment.
The main goal of ...
(wasm), which has a bytecode format that is faster to parse. Efforts to extend JavaScript with more low-level features like SIMD.js has also been suspended since 2017.
asm.js remains useful primarily as a "fallback" for wasm, through a program written by the WebAssembly organization that converts wasm to asm.js. There is no dedicated converter from asm.js to wasm, but
TypeScript
TypeScript (abbreviated as TS) is a high-level programming language that adds static typing with optional type annotations to JavaScript. It is designed for developing large applications and transpiles to JavaScript. It is developed by Micr ...
-to-wasm compilers can be partially used. The reference WebAssembly emitter, , used to contain an module, but it was removed after Emscripten stopped using it.
[ (See also th]
PR#3042
)
See also
*
CrossBridge
*
RPython
*
AssemblyScript
AssemblyScript is a TypeScript-based programming language that is optimized for, and statically compiled to, WebAssembly (currently using , the reference AssemblyScript compiler). Resembling ECMAScript and JavaScript, but with static data ty ...
References
External links
*
{{Mozilla
JavaScript
Mozilla
Web programming
Articles with example C code