【问题标题】:Find/Children vs descendant selector jquery performance differences查找/儿童与后代选择器 jquery 性能差异
【发布时间】:2012-11-23 09:16:18
【问题描述】:

我试图理解为什么this jsperf test 中的一个 sn-ps 似乎比其他的慢得多。

这是四个sn-ps:

$(".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();

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

【问题讨论】:

标签: jquery performance jquery-selectors


【解决方案1】:

是什么让第二个与众不同?

$('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
    ...

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

【讨论】:

  • 在使用 find 时是否有更有效的方法来获得相同的结果? (或者改正我的问题,既然它更慢,为什么还要使用 find ?)
  • @GeorgeKatsanos 通常单个选择器执行得更快。但是,在某些情况下,find 可能是灵丹妙药。所以,我的回答是:视情况而定。
  • 在这里浏览了许多类似的问题后,假设场景的基准测试似乎没有多大帮助,因为结果因 HTML、浏览器、机器等而异。
  • @GeorgeKatsanos 正是如此。
【解决方案2】:

孩子的数量很重要。

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

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

这是因为 children() 会遍历所有子元素来测试给定的选择器。

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多