jQuery Caching & traversing Objects

I'm trying to get my head around jQuery caching and how it improves performance and how it should be used?

As I understand it, when you use a jQuery selector you are searching the DOM and creating a jQuery object which you can traverse. Does that mean if you create a jQuery object of the html body tag you can avoid the need to traverse the DOM when creating new jQuery objects? Would there be any point to doing that?

Considering ...

var htmlBody = $('body');
$('header',htmlBody).css('background','green');
$('footer',htmlBody).css('background','yellow');

Would the above piece of code be cheaper/use less resources than...

$('header').css('background','green');
$('footer').css('background','yellow');

Answers


The first thing you have to understand is that DOM access is expensive. It is considered to be one of the most common causes of poor performance.

Consider the following code:

var elem = document.getElementByTagName('p'),
    i;

for (i = 0; i < document.getElementByTagName('p').lenght; i++) {   
    elem[i].innerHtml = 'foo';
}

And the alternative using the cached lenght

var elem = document.getElementByTagName('p'),
    i;

for (i = 0; i < elem.lenght; i++) {   
    elem[i].innerHtml = 'foo';
}

The second case will run faster in all browsers (two times faster in Safari 3 and 190 times in IE7. And this is only by using a cached value of the lenght in a loop.

Jquery provides a better API to access and manipulate the DOM but under the hoods still relies on the native API to do the job. Your considerations for performance must be based not on how many variables you have but instead how fast your code will run. Some of this points will help you

  • Avoiding DOM access in loops
  • Assigning DOM references to local variables and working with the locals
  • Caching the length when iterating over HTML collections

In other words if you use JQuery to select an element and need to access some of the elements previously selected you will get a boost of performance if use the variable instead of transversing the DOM again.


Need Your Help

How to keep scroll position in SimpleModal dialog

jquery dialog scroll modal-dialog simplemodal

How is it possible to keep the scroll position of a scrollable div within a modal dialog when it is re-opened?

How do I use popover from Twitter Bootstrap to display checkboxes, div blocks, radios, images , any?

javascript jquery html css twitter-bootstrap

How do I use popover from Twitter Bootstrap to display checkboxes, div blocks, radios, images , any?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.