Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

5.13. Reducing Name Lookups

Problem

Your code has an inner loop, down inside several levels of nested functions, that runs hundreds or thousands of times. The inner loop calls several global functions, and it references some variables defined in the outer functions or globally.

Each of these references is triggering several name lookups because of the nested functions. It’s slowing down your code, but profilers don’t show what the problem is, and it isn’t obvious from looking at the code that there’s a problem!

Solution

Investigate every name that appears in your innermost loop, and figure out how many name lookups it requires. Reduce the number of name lookups by caching object references locally or using fewer nested functions.

Discussion

Closures are a wonderful thing. They make it trivial to capture state information and pass it along to asynchronous functions such as event handlers or timer callbacks. If JavaScript didn’t have closures, then every asynchronous callback would need to have a way to pass that state around. Instead, you can simply use a nested function.

The dynamic nature of JavaScript is also a wonderful thing. You can add properties and methods to any object, any time, and the JavaScript runtime will happily chase down those references when you need them.

Put these together, and you can get a lot of name lookups.

Note

The most modern JavaScript interpreters have improved greatly in this area. But if you want your code to run fast in the most popular browsers—such as any ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required