简体   繁体   English

jQuery后代选择器性能

[英]jQuery Descendant Selector Performance

I have a jQuery selector: 我有一个jQuery选择器:

$('#myId span')

Is that really a performance dog vs: 那真的是性能狗vs:

$('#myId').find('span')

The first is obviously a bit cleaner to write and I'd like to stick with that if possible. 首先显然是写起来比较干净,如果可能的话,我想坚持下去。

Test: http://jsperf.com/descend-from-id-vs-select-and-find/3 测试: http//jsperf.com/descend-from-id-vs-select-and-find/3

$('#myId span') will cause jQuery to parse the string using its Sizzle selector engine, reading it from right-to-left, beginning its search with span . $('#myId span')将使jQuery使用其Sizzle选择器引擎解析字符串,从右到左读取它,并从span开始搜索。

$('#myId').find('span') will cause jQuery to select #myId immediately (bypassing the step to parse with Sizzle), and then traverse down the DOM, multiple levels, to find all descendants. $('#myId').find('span')将使jQuery立即选择#myId(绕过使用Sizzle解析的步骤),然后遍历DOM(多个级别)以查找所有后代。

So the latter is faster. 因此后者更快。

You could also try $('#myId').children('span') , which might be even faster in some cases, since it will only descend a single level to find children only (as opposed to find, which keeps going). 您还可以尝试$('#myId').children('span') ,在某些情况下可能会更快,因为它只会下降一个级别来仅查找子级(而不是find,因此会一直运行) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM