Friday, April 11, 2014

Writing Fast Javascript - Compiler Optimization (V8, Node.js)

Understanding how a compiler optimizes code can add significantly increase the efficiency of code.  Working within a team we've run into all kinds of styles/preferences of Javascript code.  Of course, with a language like Javascript it's important to understand that one style/preference can have penalties.
So for the last few years, Lars Bak has been getting a bit of attention for bringing speed to Javascript through the implementation of OOP compiler technology to the Javascript JIT (Just-In-Time compiler) in V8.  Bak worked on several compilers in the past and has a great deal of experience he brings from writing many VM's.

V8 has been making waves through Google's mail service, Gmail, and their suite of office apps, Google Docs.

Considering the idea of creating Objects dynamically:

var point1 = {
   x: 1,
   y: 2

And modifying them:

point1.x = 5;

It's important to note the way these optimizations work is through an assumption that dynamic languages have a inherit structure.  And the JIT in V8 takes advantage of this structure.

Writing a function such as:

function Point(x, y) { ...

Causes the JIT to create a class definition.  Assigning values within that function:

function Point(x, y) {
  this.x = x;
  this.y = y;

Then signals to the JIT to transition the class to a class definition with specific parameters this.x and this.y.

This allows the engine to run highly optimized.  V8 does not use the traditional technique of compiling Javascript to intermediary bytecode but instead compiles Javascript to native machine code.

Changing the structure of an object can cause it to degrade into a hash, which is tremendously slow.

I'd love to see how Dart makes headway and changes the landscape for Javascript.

Here Lars Bak talks about some optimizations in V8:

No comments: