3 ms·
The main slowdown in JavaScript is because it is inherently so dynamic — all function calls are "virtual," properties are string lookups, you need a lot of indi
by tylerhou 5y ago
The main slowdown in JavaScript is because it is inherently so dynamic — all function calls are "virtual," properties are string lookups, you need a lot of indirection (boxing) to store objects. Without actually running the program on some input, it is infeasible to determine what those indirections will resolve to. So static compilation is useless (or would produce instructions very similar to what an interpreter would execute). That's why we usually interpret the code (and JIT it to optimize places where the program is not actually dynamic).
Theoretically you could "precompile" JavaScript by running your code on some known input and caching the VM's state. Then you can "hydrate" your VM with that state. But this would only speed up the VM warmup (which is not that long) and requires significant browser/VM buy-in, so it is probably infeasible.
The only way to produce better performance in JavaScript is to restrict it to a less-dynamic subset (e.g. objects must have static keys) and add at least some static typing so that a compiler can resolve some references ahead of time. That's why asm.js was a thing. But asm.js has been superseded by WASM, which better in most regards.
- vlovich123 5y agoHave you seen the work Fastly discussed about their AOT compiler? Seems like an interesting approach that maybe could be used to preprocess code into a more efficient form before running it in the cloud. The challenge is that JS engines are primarily focused on the browser and such an optimization opportunity isn’t interesting there - the majority of development is done by browser vendors.