Node.js Under The Hood #10 - Compiler Optimizations!
Tags: node, v8, computerscience, javascript
Published: 2020-04-06 13:42:11

_Photo by Michael Dziedzic on Unsplash_

In our previous articles, we talked about how [Node.js](https://docs.microsoft.com/azure/javascript/?WT.mc_id=nodeunder-devto-ludossan) worked under the hood and how V8 compiled the code so efficiently, most of that efficiency is related to [compiler optimizations](https://docs.microsoft.com/archive/msdn-magazine/2015/february/compilers-what-every-programmer-should-know-about-compiler-optimizations?WT.mc_id=nodeunder-devto-ludossan), so in this article, we'll finally get to know what are those and how they work!

This is a brief summary of several [compiler optimizations](https://docs.microsoft.com/archive/msdn-magazine/2015/february/compilers-what-every-programmer-should-know-about-compiler-optimizations?WT.mc_id=nodeunder-devto-ludossan) V8 might perform in the code. The whole point of this article is only to introduce what sort of things are included when we say "optimization". We won't be digging deeper into how compilers do this.

All of the optimizations below are done while the compiler is analyzing the code.

## On Stack Replacement

On Stack Replacement is the optimization technique that replaces a chunk of not-optimized code by another chunk of optimised code during execution. V8 does that every time it needs to optimize a single function or the running code. In short, on stack replacement means that the current stack frame will be replaced by another stack frame of optimised code without losing any other information and while the code is still executing. It's like changing the tires of a car in the middle of a race without stopping.

## Constant Folding

Replaces constant expressions by their final value at compile-time, rather than doing the calculation at run-time.

Example:

*not compiled:*

```js
const j = 3 + 9
```

*compiled:*

```js
const j = 12
```

## Induction Variable Analysis

In a loop, if a variable is a simple linear function of the index variable, for instance, `const p = 4 * i +1` then it can be updated appropriately each time the loop variable is changed.

This is what is called a strength reduction, a form of optimisation where costly operations are replaced by equivalent less costly ones, for instance, a costly multiplication is replaced by a series of cheaper additions.

## Rematerialization

The act of recalculating a value instead of loading it from memory, which prevents memory access to be performed too many times.

## Removing Recursion

Recursion is often very expensive, as we saw about stack overflows. Tail recursive algorithms (code that ends returning a call to itself) can be converted to iterative algorithms, which eliminates the stack problems. This is often done by using **[Tail Call Optimisations](https://en.wikipedia.org/wiki/Tail_call)**, which is the process where you are able to avoid allocation a new stack frame for a function because the calling function will simply return the value that it gets from the called function. So this last call can be replaced by the function itself.

## Peephole Optimisations

These are usually performed late in the compilation process after the machine code has been generated. This optimisation technique examines a few adjacent instructions (like looking through a peephole) to see if they can be replaced by a single instruction or a shorter sequence of instructions. An example is a multiplication by a power of 2, which can be replaced by a bitwise left-shift. (which is also a strength reduction optimisation)

### Inline Expansion

This is the technique of replacing the call to a function by its body. This saves the overhead of adding another stack frame and also adds a great opportunity for parameter specific optimisations, but this comes at the cost of space. If the procedure is called several times during a program, its body will be replaced several times, which can lead to a bigger, heavier code.

Generally, inlining is very useful to performance-critical code that makes a large number of calls to small procedures, so there are fewer jumps.

## Inline Caching

Inline caching relies on the observation that repeated calls to the same method tend to occur on the same type of object. V8 maintains a cache of the type of objects that were passed as a parameter in recent method calls and uses this information to make an assumption about the type of object that'll be passed as a parameter in the future. If this assumption is good, then the next call can bypass the process of figuring out how to access the object's properties and, instead, use the stored information from precious lookups to the hidden class of that object.

This relates specifically to the concept of hidden classes because whenever a method is called on a specific object, the engine has to lookup the hidden class in order to find the memory offset for such called property. After two successful calls of that same method to the same hidden class, V8 omits the hidden class lookup and adds the offset to that property to the object pointer itself. This greatly increases execution speed.

## Dead Code Elimination

This process eliminates code that is never called in the program. It does this, roughly, by passing through all bytecodes during program execution, generates a graph and eliminates those parts which do not belong to any code path.

## Code Block Reordering

Code-block reordering alters the order of the basic blocks in a program in order to reduce conditional branches and improve locality of reference, which is the tendency of a processor to access the same set of memory locations repetitively over a short period of time.

## Jump Threading

Consecutive conditional jumps predicated entirely or partially on the same condition can be merged. E.g: `if (c) { foo; } if (c) { bar; }` becomes `if (c) { foo; bar; }`

## Trampolines

Many CPUs have smaller subroutines call instructions in order to access low memory. The compiler can save space using these small calls in the function's body. Multiplying space savings from code refactoring.

## Common subexpression elimination

Whenever we have repeated subexpressions, like in `(a+b) * 2+(a+b)`, the *common subexpression* is `a+b`. So, the compiler calculates the value of `a+b` only once and uses *constant folding* to replace it in the expression call, assuming the common subexpression will **not** change.

# Conclusion

You DID IT! You finally got to the end of our 10 part long series about Node.js under the hood! I hope you liked it and felt a little more excited to learn more!

Below I'll leave all the references I used to compose all those articles and also a link to [the original article draft on my GitHub](https://github.com/khaosdoctor/my-notes/blob/master/node/node-under-the-hood.md). That's it! Thanks a lot for reading and giving me feedback about it :D

# References

- [LibUV](https://github.com/libuv/libuv?WT.mc_id=devto-blog-ludossan)
- [N-API](https://nodejs.org/api/n-api.html)
- [Esprima AST generator](https://esprima.org)
- [TurboFan docs](https://v8.dev/docs/turbofan)
- [TurboFan JIT](https://v8.dev/blog/turbofan-jit)
- [Native modules](https://nodejs.org/api/addons.html)
- [JS History](https://en.wikipedia.org/wiki/JavaScript)
- [Node.js history](https://en.wikipedia.org/wiki/Node.js)
- [Element Kinds in V8](https://v8.dev/blog/elements-kinds)
- [WHATVG spec on microtasks](https://html.spec.whatwg.org/multipage/webappapis.html#task-queue)
- [V8 Under the Hood](https://slides.com/igorfranca/v8-under-the-hood#/)
- [FS module source](https://github.com/nodejs/node/blob/master/lib/fs.js?WT.mc_id=devto-blog-ludossan)
- [TurboFan creation motives and performance reasons](https://nodesource.com/blog/why-the-new-v8-is-so-damn-fast/)
- [FS read_file_context source](https://github.com/nodejs/node/blob/master/lib/internal/fs/read_file_context.js?WT.mc_id=devto-blog-ludossan)
- [V8 Under The Hood Examples](https://github.com/Horaddrim/v8-under-the-hood?WT.mc_id=devto-blog-ludossan)
- [Internals of Node with crypto library](https://medium.com/front-end-weekly/internals-of-node-advance-node-%EF%B8%8F-8612f6a957d7)
- [Microtasks and Macrotasks](https://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context)
- [Lauching ignition and turbofan](https://v8.dev/blog/launching-ignition-and-turbofan)
- [Performance Optimisations in V8](https://v8-io12.appspot.com/index.html)
- [In-Depth of Inline caching](https://github.com/sq/JSIL/wiki/Optimizing-dynamic-JavaScript-with-inline-caches?WT.mc_id=devto-blog-ludossan)
- [Sea of Nodes approach](http://www.masonchang.com/blog/2010/8/9/sea-of-nodes-compilation-approach.html)
- [Sea of Nodes explanation](http://grothoff.org/christian/teaching/2007/3353/papers/click95simple.pdf)
- [How to get bytecode from NodeJS](https://medium.com/@drag13dev/https-medium-com-drag13dev-how-to-get-javascript-bytecode-from-nodejs-7bd396805d30)
- [Understanding V8 Bytecodes](https://medium.com/dailyjs/understanding-v8s-bytecode-317d46c94775)
- [V8 Bytecode List](https://github.com/v8/v8/blob/master/src/interpreter/bytecodes.h)
- [How Node's GC Works](https://blog.risingstack.com/finding-a-memory-leak-in-node-js/)
- [V8 Interpreter Generator](https://github.com/v8/v8/blob/master/src/interpreter/interpreter-generator.cc?WT.mc_id=devto-blog-ludossan)
- [What are Stacks?](https://en.wikipedia.org/wiki/Stack_(abstract_data_type))
- [What are queues?](https://www.studytonight.com/data-structures/queue-data-structure)
- [Compiler Optimisation list](https://en.wikipedia.org/wiki/Optimizing_compiler)
- [What are Static Single Assignments?](https://wingolog.org/archives/2011/07/12/static-single-assignment-for-functional-programmers)
- [On stack replacement in V8](https://wingolog.org/archives/2011/06/20/on-stack-replacement-in-v8)
- [Why is Node.js so Fast](https://blog.ghaiklor.com/2015/11/14/why-nodejs-is-so-fast/)
- [You don't know Node.js](https://medium.com/edge-coders/you-dont-know-node-6515a658a1ed)
- [V8 - A tale of Turbofan](https://dzone.com/articles/v8-behind-the-scenes-and-a-tale-of-turbofan)
- [Optimisation tricks in V8](https://blog.ghaiklor.com/2016/04/05/optimisations-tricks-in-v8/)
- [V8 Internals for Developers](https://slidr.io/mathiasbynens/v8-internals-for-javascript-developers#1)
- [How V8 Optimizes the Code](https://blog.ghaiklor.com/2016/03/25/how-v8-optimises-javascript-code/)
- [My personal notes (in Portuguese) about V8](https://github.com/khaosdoctor/my-notes/blob/master/node/V8.md?WT.mc_id=devto-blog-ludossan)
- [[BOOK] Node.js Under the Hood](https://resources.risingstack.com/Node.js+at+Scale+Vol.+2+-+Node.js+Under+the+Hood.pdf)
- [Tracing de-optimisations in Node.js](https://blog.ghaiklor.com/2016/05/16/tracing-de-optimisations-in-nodejs/)
- [Understanding Promises Once and for All](https://medium.com/trainingcenter/entendendo-promises-de-uma-vez-por-todas-32442ec725c2)
- [JS Rendering Engine](https://blog.sessionstack.com/how-javascript-works-the-rendering-engine-and-tips-to-optimize-its-performance-7b95553baeda)
- [Memory Allocation in Javascript](https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec)
- [How JavaScript works: an overview of the engine, the runtime, and the call stack](https://blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf)
- [My talk guidelines (first version, incomplete, also in Portuguese) about this topic](https://github.com/khaosdoctor/my-notes/blob/master/node/Guideline%20de%20palestra%20the%20conf%202019.pdf?WT.mc_id=devto-blog-ludossan)
- [How JavaScript works: inside the V8 engine + 5 tips on how to write optimized code](https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e)
- [[VIDEO] High performance JS in V8](https://www.youtube.com/watch?v=YqOhBezMx1o)
- [[VIDEO] Ryan Dahl's Introduction to Node.js](https://www.youtube.com/watch?v=jo_B4LTHi3I)
- [[VIDEO] BlinkOn 6 Day 1 Talk 2: Ignition - an interpreter for V8](https://www.youtube.com/watch?v=r5OWCtuKiAk)
- [[VIDEO] MNUG 2017.03.23 TurboFan: A new code generation architecture for V8](https://www.youtube.com/watch?v=M1FBosB5tjM)
- [[VIDEO] Benedikt Meurer: A Tale of TurboFan: Four years that changed V8 forever](https://www.youtube.com/watch?v=cvybnv79Sek)
- [[VIDEO] Marja Hölttä: Parsing JavaScript - better lazy than eager? | JSConf EU 2017](https://www.youtube.com/watch?v=Fg7niTmNNLg)
- [VIDEO] [Franziska Hinkelmann](https://dev.to/fhinkel): [JavaScript engines - how do they even? | JSConf EU 2017](https://www.youtube.com/watch?v=p-iiEDtpy6I?WT.mc_id=devto-blog-ludossan)
- [[VIDEO] TDC 2017 - Stadium: How Node.js Works Internally by Kirmayr Tomaz (in Portuguese)](https://pt-br.eventials.com/Globalcode/tdc-sp-2017-stadium-quarta-5/?WT.mc_id=devto-blog-ludossan)