To understand better about the previous examples of physics in JavaScript, I decided to learn how chrome handles JavaScript. V8 is the open source JavaScript engine developed by Google for chrome. Written in C++, the engine was created for high performance. It implements three key design aspects that are responsible for its considerable performance. By a glancing comparison, Chrome appears to be faster than all of its competitors.
The three key design aspects for v8 are:
- Fast Property Access
- Dynamic Machine Code Generation
- Efficient Garbage Collection
Fast Property Access
JavaScript dynamically controls its properties allowing an object to add or remove properties on the fly. JavaScript typically uses a dictionary-like object to hold an object and its properties. Most JavaScript engines access these dictionary objects by dynamic lookup. Dictionary lookup is generally slower and should be avoided. V8 handles this by creating hidden classes.
For example, a function, point, was created with two properties.
function Point(x, y) {
this.x = x;
this.y = y;
}
 |
First, hidden class for point is created |

|
When this.x = x; is accessed, the initial class is reused by adding another hidden class with directions to access the property |
|
 |
When this.y = y; is accessed,anther class is made with offset directions |
Every
point object used after this initialization will refer to class C0, and any property access for
x or y will refer to the hidden class that holds the directions to the memory holding it.
Dynamic Machine Code Generation
As opposed to intermediate byte code, v8 directly translates JavaScript to machine code. Inline caching is used for property access that can later be dynamically changed. The inline caching attempts to predict future calls to a lookup and place the results for easy access. There are cases where the optimization would fail, so the runtime temporarily pulls out of the optimized code to patch the problem. If the patching fails, the unoptimized code runs.
Efficient Garbage Collection
V8 employs stop-the-world, generational, accurate, garbage collection which means it does several things:
- stops program execution when performing a garbage collection cycle.
- processes only part of the object heap in most garbage collection cycles. This minimizes the impact of stopping the application.
- always knows exactly where all objects and pointers are in memory. This avoids falsely identifying objects as pointers which can result in memory leaks.