3

我试图理解为什么这个 jsperf 测试中的一个片段似乎比其他片段慢得多。

这是四个片段:

$(".menu-vertical li.selected > ul.static").show().parents().show();

$('ul.root').find('li.selected').children('ul.static').show().parents().show();

$("ul.root li.selected > ul.static").show().parents().show();

$('ul.root li.selected').children('ul.static').show().parents().show();

第二个似乎在所有浏览器中始终较慢,我不明白为什么。

4

2 回答 2

3

是什么让第二个与其他人不同?

$('ul.root')               // you get the collection of all `ul.root`
    .find('li.selected')   // in each collection you search for `li.selected`
    .children('ul.static') // you get `ul.static` children elements of each found
    ...

请注意您需要进行多少次迭代。在所有其他示例中,大部分搜索都是在单个查询中执行的,该查询的评估速度要快很多倍。

于 2012-12-05T14:12:04.140 回答
0

孩子的数量很重要。

有很多(比如>10)孩子$el.find('> selector')表现更好

带几个孩子$el.children('selector')表现更好。

这是因为 children() 遍历所有子项以测试给定的选择器。

于 2015-12-21T12:37:22.070 回答