Why was the V8 Engine created?
The engine used two compilers -
Full-codegen - a simple and very fast compiler that produced simple and relatively slow machine code.
Crankshaft - a more complex (Just-In-Time) optimizing compiler that produced highly-optimized code.
V8 uses two different methods to handle arrays -
Fast elements - Designed for arrays where the set of keys are very compact. They have a linear storage buffer that can be accessed very efficiently.
Dictionary elements - Designed for sparse arrays which don’t have every element inside of them. It is actually a hash table, more expensive to access than “Fast Elements”
V8 uses “Fast Elements” to handle arrays, in other words, avoid sparse arrays where keys are not next incremental numbers. Also, try to avoid pre-allocating large arrays. It is better to grow as you go.
Accessing types and properties effectively makes a first big challenge for V8. Instead of using a dictionary-like data structure for storing object properties and doing a dynamic lookup to resolve the property location, V8 creates hidden classes, at runtime, in order to have an internal representation of the type system and to improve the property access time.
V8 creates a new hidden class everytime the constructor function declares a property and keeps track of the change in the hidden class. Why? Because if two objects are created (m and n) and if a member is added to the second object (n) after the creation, V8 needs to keep the last hidden class created (for the first object m) and to create a new one (for the second object n) with the new member.
V8 also supports de-optimization: the optimizing compiler makes optimistic assumptions from the Inline Cache about the different types, de-optimization comes if these assumptions are invalid. For example, if a hidden class generated was not the one expected, V8 throws away the optimized code and comes back to the Full Compiler to get types again from the Inline Cache. This process is slow and should be avoided by trying to not change functions after they are optimized.