The JavaScript engine handles optimization better than before

May 2, 2012 20:01 GMT  ·  By

Google is bragging about a new improvement to the V8 JavaScript engine in Chrome. The engine can be considered state-of-the-art, but the technology is not standing still. The latest additions improve the way V8 optimizes code, especially for short running scripts.

The improvements should result in more optimized code, with less of an overhead, aka better performance at a low cost. The change leads to a 25 percent improvement in SunSpider score.

"When executing JavaScript, V8 at first compiles it to machine code with a very fast compiler that doesn't optimize the code it produces," Google explained.

"V8 has a second, optimizing compiler that generates much faster machine code, but takes much more time to do so, so it has to be used selectively," it added.

The obvious challenge is to find the functions that would benefit from the optimization and discard the rest. Of course, V8 has to do this without interfering with the running code too much.

Currently, in Chrome 18, V8 stops every millisecond, which may seem like a very short amount of time, but code is processed a lot faster than that. When it stops, it analyzes the currently running functions and decides which would benefit the most from optimization.

That works for long-running programs, but short functions, which may be used often, don't get optimized.

As of Chrome 19, V8 analyzes scripts more often and in greater detail to make more informed decision on what to optimize.

"It uses counters to keep track of how often JavaScript functions are called and loops are executed in a program, approximating the time spent inside each function," Google's Jakob Kummerow, a software engineer, wrote.

"That way V8 is able to quickly gather fine-grained information about performance bottlenecks in a JavaScript program, and to make sure that the optimizing compiler's efforts are spent on those functions that deserve it most," he added.