I've created a jsfiddle here: http://jsfiddle.net/2tfbs/1/
Since the scope for 'find' is smaller in the bottom loop, why is the speed so much slower? If you change the jQuery versions there's a performance hit (a massive one in Firefox 5) going from 1.4.4 and onward but in all versions the conclusion is basically the same.
If you change the first loop to simply $('#container') and not a cached variable, the result is also the same and seemingly contradicts everything I've read that says "caching is faster".
Am I doing something wrong? I don't understand what's going on.
Edit: Code from the jsfiddle
html:
<div id="container">
<div class="post">
<div class="content"&开发者_如何学JAVAgt;
<span></span>
</div>
<div class="meta">
<span></span>
</div>
</div>
+2 more iterations of a post block
</div>
js:
//first loop
var $container = $('#container');
var i = 1000,
a, start1 = new Date();
while (i--) {
a = $container.find('div.content');
}
var end1 = new Date();
$('#one').text((end1 - start1) / 1000);
//second loop
var $post = $container.find('div.post');
var j = 1000,
b, start2 = new Date();
while (j--) {
b = $post.find('div.content');
}
var end2 = new Date();
$('#two').text((end2 - start2) / 1000);
Because you are running find()
against multiple elements in the second loop.
In the first loop, your selector matches a single element (you have a single #container
). In the second loop, your selector matches multiple elements (you have numerous div.content
). More elements means more matching means more cycles.
精彩评论