jQuery: improving performance

jQuery is a powerful JavaScript framework but, nonetheless, is still JavaScript, so the rules for improving your JavaScript performance also apply to jQuery, with some differences. jQuery has its own peculiar constructs that need to be improved from a performance perspective. In this post I'm going to discuss with you some interesting points for improving jQuery's performance.

Loops

jQuery's loops come in the form of $.each() and each(), respectively. As a rule of thumb, you should use these two loops only when strictly necessary, because they actually affect performance in a significant way. They are not as normal for loops, because JavaScript's for loops are written and implemented in C/C++ so they are much more faster to execute. For example, do not do this:

$('#list li').each(function() {
   $(this).addClass('test');
});

If your goal is simply add a CSS class, you can get the same result with the following code:

var items = $('#list li').get(), i, len = items.length;
for( i = 0; i < len; i += 1) {
  items[i].className = 'test';
}

This is much faster than the preceding example, especially when we have a lot of items. So remember: use jQuery's loops only when necessary; in all other cases use JavaScript's core loops.. If you use jQuery's loops, a way to improve performance is to cache the significant elements within a loop into variables:

$('#list li').each(function() {
    var $li = $(this);
    $li.addClass('test');
});

HTML content

jQuery controls the HTML content of an element through the html() method. This method makes use of the innerHTML property to set or get the HTML content of page elements. As said before, html() and innerHTML are not the same thing from a performance perspective. While the former is a jQuery wrapper, the latter is actually implemented in C/C++ by calling the SGML parser of a web browser, thus resulting in a lightning speed.

So, use innerHTML whenever it's possible by paying a special attention on how this property is used. For example, do not do this:

var element = $('#test')[0], i;

for(i = 0; i < 10; i += 1) {
  element.innerHTML += i;
}

This will result in ten calls to the browser's SGML parser. Instead, use the following approach:


var element = $('#test')[0], i, html = '';

for(i = 0; i < 10; i += 1) {
    html += i;
}

element.innerHTML = html;

In this case, we have only a single call to the browser's SGML parser, thus resulting in a better performance.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.