JQuery Find Performance

I find this:

var $colSelect = $('#stuff').find('.things'); $($colSelect).find('img, input, select').addClass("foo"); 

slower than this:

 var $colSelect = $('#stuff').find('.things'); $($colSelect).find('img').addClass("foo"); $($colSelect).find('input').addClass("foo"); $($colSelect).find('select').addClass("foo"); 

Can someone help me understand why this is so? In particular, I see a performance improvement in IE8.

+7
source share
4 answers

I assume that for the first selector, jQuery should parse the selector, call getElementsByTagName JavaScript for everyone and join the results (maybe even arrange them in the order of their position in the DOM).

The second case has direct JavaScript calls to getElementsByTagName , without any other operations.

This page compares specifications: http://jsperf.com/jquery-selector-performance-problems

+3
source

Update 2: Changed to reflect the grid, as the nature of what you have. Here are my results with jQuery 1.7.1 (one of them is your upper code, two is your lower code). I took only the five slowest things, because everything else did not matter.

Results compareing the two algorithms

As you can see, the reason one is probably slower than the other is because of the sortOrder function (minified as U) and / or Array.sort. Both of them do not even appear in Two. The problem, of course, is the need to return and sort the results. makeArray (as stated above) seems to take less time in 1, but this does not compensate for the sorting that needs to be done.

Update: I created jsFiddle to play with it , and I do not see a noticeable difference in IE8 between the two methods. It may need more context for what this page looks like / which styles are applied. This may have something to do with browser rendering, resulting in your code acting differently.

IE8 has a built-in profiler.

  • Go to Developer Tools (F12)
  • Click the Profile tab.
  • Click the start button
  • Do JavaScript work if you need to do
  • Click Stop and analyze the results. Look for things that are slow. Correct them.
  • Repeat

Tips to improve your javascript. Try not to call $ ($ colSelect) all the time. Save it so that the variable.

 var $colSelect = $($('#stuff').find('.things')); 
+2
source

in the second case, the DOM subtree under $ colSelect will be traversed three times. That is why it will be slow.

0
source

How about this?

 $('#stuff .things') .find('img').addClass("foo").end() // .end() returns to '#stuff .things' .find('input').addClass("foo").end() .find('select').addClass("foo"); 
0
source

All Articles