๐ง๐ต๐ถ๐ ๐๐ ๐๐ผ๐ ๐ฉ๐ด ๐ข๐ฝ๐๐ถ๐บ๐ถ๐๐ฒ๐ ๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ You use JavaScript to build complex web applications and games. But have you ever wondered how JavaScript runs so fast? V8 performs a lot of optimization behind the scenes. Here's what you need to know:
- Why dynamic languages are hard to optimize
- What JIT compilation is
- How Ignition and TurboFan work together
- What hidden classes are
- How inline caches improve performance
- Why deoptimization happens V8 makes assumptions based on observed behavior. For example: "This variable has always contained numbers." As long as those assumptions remain true, V8 can generate highly optimized machine code. If the assumptions later become invalid, V8 falls back to a slower execution path. One key technology behind V8's performance is Just-In-Time (JIT) compilation. JIT combines elements of two approaches:
- Execute code line by line during runtime
- Convert source code into machine code before execution Modern V8 uses two major components:
- Ignition: V8's interpreter
- TurboFan: V8's optimizing compiler They form a two-stage execution pipeline. Ignition starts execution quickly and collects runtime information. TurboFan detects hot code paths and applies advanced optimizations. Hidden classes provide predictability. They treat JavaScript objects as if they had fixed structures. Inline caches store information about previous property lookups. They reduce property access overhead. When object shapes remain consistent:
- Hidden classes remain stable
- Inline caches stay valid
- Performance improves When object shapes change frequently:
- New hidden classes are created
- Cached information becomes invalid
- Performance may decrease Deoptimization happens when V8's assumptions become wrong. This can be triggered by type changes, object shape changes, or mixed array element types. To write code that works with V8, keep the following in mind:
- Keep types consistent
- Keep object shapes consistent
- Avoid unnecessary type changes
- Avoid mixing different types within arrays Predictable code is easier for V8 to optimize. Source: https://dev.to/bysontech_8dd1313811a8895/understanding-how-javascript-runs-in-the-browser-v8-rendering-engines-and-devtools-42oj