Optimizing JavaScript for runtime speed (Yetihq.com)

posted in: Uncategorized | 0
[Published on Yetihq.com]

This summer Brandon Jones of Motorola Mobility presented a talk about efficient JavaScript vector math [1]. The concepts presented in this JavaScript meetup talk are beneficial to make JavaScript run faster in any codebase. Here are some of the principles that a developer should take:

1. Cache variable calls instead of making multiple separate calls. For example,

should be written as:

This code is faster because the method lookup on the object only has to be performed once.

2. Write your APIs (application programming interfaces) as function methods not objects.

should be written as:

This code is faster because we are not copying all the function pointers in the object hashtable. Only the values that change between each instance are copied.

3. Inline code rather than writing function calls. Compilers in the early days weren’t good at optimizing certain function calls, but they’ve improved over time now. JavaScript runtime compilers, however, aren’t at that level yet.

should be written as:

This code is faster because a function call requires its own execution context (stack frame). Without a function call this extra stack frame isn’t needed.

4. Unroll your loops. This concept refers to pipelining instructions without branch conditions. Branch conditions often appear in loops, which prevents the compiler from predicting the code path of execution. Have a look at the example from Brandon (below).

This code should be written unrolled.

The code is much faster because bounds checking (i.e., the branch condition) is checked once at the beginning rather than on every call.

5. Use native arrays when performing computation-intensive operations on floating-point numbers. Float32Array is very fast to use but incredibly expensive to create. In other words, reuse and cache floating-point array objects and don’t create them inside a loop.

In summary these optimizations are workarounds to JavaScript’s non-optimizing compiler. Modern C and Java compilers are able to circumvent some of these issues but web browser JavaScript engines aren’t as smart yet. Happy optimizing!

[1] http://media.tojicode.com/sfjs-vectors/