Disclaimer:- This article is a mixture of
- V8 — open-source, developed by Google, written in C++
- Rhino — managed by the Mozilla Foundation, open-source, developed entirely in Java
- KJS — KDE’s engine originally developed by Harri Porten for the KDE project’s Konqueror web browser
- Chakra (JScript9) — Internet Explorer
- Nashorn, open-source as part of OpenJDK, written by Oracle Java Languages and Tool Group
- JerryScript — is a lightweight engine for the Internet of Things.
We will be discussing mostly Chrome V8 Engine.
The Chrome V8 engine :
- The V8 engine is written in C++ and used in Chrome and Nodejs.
- It implements ECMAScript as specified in ECMA-262.
- The V8 engine can run standalone we can embed it with our own C++ program.
So for example:
Node.js in itself is a C++ implementation of a V8 engine allowing server-side programming and networking applications.
Order of object properties: always instantiate your object properties in the same order so that hidden clauses, and subsequently optimized code, can be shared.
Dynamic properties: adding properties to an object after instantiation will force a hidden class change and slow down any methods that were optimized for the previously hidden class. Instead, assign all of an object’s properties in its constructor.
Methods: code that executes the same method repeatedly will run faster than code that executes many different methods only once (due to inline caching).
Arrays: avoid sparse arrays where keys are not incremental numbers. Sparse arrays that don’t have every element inside them are a hash table. Elements in such arrays are more expensive to access. Also, try to avoid pre-allocating large arrays. It’s better to grow as you go. Finally, don’t delete elements in arrays. It makes the keys sparse.
Tagged values: V8 represents objects and numbers with 32 bits. It uses a bit to know if it is an object (flag = 1) or an integer (flag = 0) called SMI (SMall Integer) because of its 31 bits. Then, if a numeric value is bigger than 31 bits, V8 will box the number, turning it into a double and creating a new object to put the number inside. Try to use 31 bit signed numbers whenever possible to avoid the expensive boxing operation into a JS object.