Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's faster $("s1").find("s2").find("s3") or $("s1 s2 s3")?

jQuery is quite multifaceted when it comes to selecting certain DOM elements. Today it came to my attention that the two ways of getting the same elements may yield different speed:

$("selector1").find("selector2").find("selector3")

and

$("selector1 selector2 selector3")

(where selectorX can be ID or class or anything else)

Both produce the same set of elements but are there any speed differences? How does jQuery actually traverse DOM? This is especially important in the second case: does it go from selector1 to selector3 or the other way around?

Anybody measured the difference between the two?

like image 232
Robert Koritnik Avatar asked May 05 '11 15:05

Robert Koritnik


2 Answers

Using a single $('...') is about twice as fast as chaining $.find()s for me in Chrome. This JSPerf Benchmark will give you a good idea of other browsers as well once some more people test it.

like image 112
Jim Mitchener Avatar answered Nov 16 '22 20:11

Jim Mitchener


Time it yourself and find out!

console.time("Selector 1") 
    $("selector1").find("selector2").find("selelector3");
console.timeEnd("Selector 1")

console.time("Selector 2") 
    $("selector1 selector2 selector3");
console.timeEnd("Selector 2")
like image 22
HurnsMobile Avatar answered Nov 16 '22 21:11

HurnsMobile