Caching objects and references is a good coding practice to avoid lookups in browsers. Generally speaking, most modern browsers have significantly improved their lookups routines but not all. More specifically, IE8 and lower have still significant problems with lookups and performance. So if you want to get good results with performance, start caching!
Avoiding DOM lookups
Consider the following:
var lis = document.getElementsByTagName('li'); var divs = document.getElementsByTagName('div');
you can cache the reference to the document
object:
var $ = document; var lis = $.getElementsByTagName('li'); var divs = $.getElementsByTagName('div');
The first code sample uses two lookups, while the last one only one.
Avoiding lookups in loops
Consider the following:
for(var i = 0; i < lis.length; i += 1) { // ... }
We have two lookups here, one for the counter and one for the array's size. We can reduce them to zero:
var i, len = lis.length; for( i = 0; i < len; i += 1) { // ... }
Avoiding object lookups
Consider the following example taken from jQuery:
var A = { property: 'a' }; var B = { method: function() { console.log(this); } }; var C = $.extend(A, B);
There are several lookups here:
- access the jQuery wrapper
- access the
fn
object - find the
extend()
method - merge objects
Step #4 also requires additional steps which involve other lookups. If your goal is to simply extend one object with another, then you can use a simpler approach:
// http://pietschsoft.com/post/2009/07/29/JavaScript-Easily-Extend-an-Object-Element.aspx var extend = function(obj, extObj) { if (arguments.length > 2) { for (var a = 1; a < arguments.length; a++) { extend(obj, arguments[a]); } } else { for (var i in extObj) { obj[i] = extObj[i]; } } return obj; };