Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cost of finding a node in JQuery?

I always save the result of the find() in order to avoid multiple sub tree traversal if I need the value several times:

var $a_bar = $('div.foo').find('a.bar');
$a_bar.removeClass(...);
// ... code here
$a_bar.bazz();

instead of

$('div.foo').find('a.bar').removeClass(...);
// ... code here
$('div.foo').find('a.bar').bazz();

I am wondering if it is not a micro-optimization... So what is the cost/complexity of finding a node in JQuery?

like image 885
JohnJohnGa Avatar asked Jan 22 '13 17:01

JohnJohnGa


People also ask

What does jQuery find return?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.

How can get li id value in jQuery?

ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });

Which methods return the element as a jQuery object?

The jQuery selector finds particular DOM element(s) and wraps them with jQuery object. For example, document. getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.


2 Answers

You can test it on js perf : http://jsperf.com/ Just create a test and run it.

I have created a small test here : http://jsperf.com/jquery-find55

On my browser (firefox 18) :

  • test 1 (i save the find result) scores at 7,074 operations by second
  • test 2 (i don't save the find result) scores at 1,553 operations by second

So, yes, find is "slow" and it's definitively a good idea to store it in a variable.

like image 81
Magus Avatar answered Oct 01 '22 08:10

Magus


If you are going to be re-using variables multiple times, it is definitely a great idea to cache them like you are doing.

.find() traversing within the jQuery object you pass before it, so it only looks within what is already given, making it very fast.

var $mainElement = $('#whatever'),
    $innerLIs  = $mainElement.find('li'),
    $innerTDs  = $mainElement.find('td');

// Now that these are cached in memory, doing anything to them is very quick

$innerLIs.hide();
// etc etc

If we kept querying for them, it would have to look through the DOM each time. And once that was finished, it would be wrapping it in a jQuery object each time as well.

like image 26
Mark Pieszak - Trilon.io Avatar answered Oct 01 '22 08:10

Mark Pieszak - Trilon.io