What is fastest children() or find() in jQuery?

Viewed 253414

To select a child node in jQuery one can use children() but also find().

For example:

$(this).children('.foo');

gives the same result as:

$(this).find('.foo');

Now, which option is fastest or preferred and why?

7 Answers

children() only looks at the immediate children of the node, while find() traverses the entire DOM below the node, so children() should be faster given equivalent implementations. However, find() uses native browser methods, while children() uses JavaScript interpreted in the browser. In my experiments there isn't much performance difference in typical cases.

Which to use depends on whether you only want to consider the immediate descendants or all nodes below this one in the DOM, i.e., choose the appropriate method based on the results you desire, not the speed of the method. If performance is truly an issue, then experiment to find the best solution and use that (or see some of the benchmarks in the other answers here).

Those won't necessarily give the same result: find() will get you any descendant node, whereas children() will only get you immediate children that match.

At one point, find() was a lot slower since it had to search for every descendant node that could be a match, and not just immediate children. However, this is no longer true; find() is much quicker due to using native browser methods.

I'm sorry but my own experience will not match with most of the answers here so I think it's interesting to share it here and suggest people to do their own tests for their own usage context.

I have just gained approximatively 40% performance by replacing in several places of my script $(...).find() by $(...).children().

The actual nesting of items was really low (max 3 levels), and despite this children() is clearly much more efficient.

Both were called thousands of times to retrieve informations in a grid (made of thousands of ). The purpose is to mainly to apply some styling to cells / columns / rows depending of several things in the cell content.

With Firefox, before to replace find(), load time for the grid was between 2100 and 2400ms. After the change with children(), it was reduced to something between 1300 and 1500ms (so between 30% and 40% less).

However, with Chrome, it's not so convincing unfortunately : Chrome is much slower (8s) to process exactly the same thing, and I don't see any obvious performance difference before and after this change with it.

Related