【问题标题】:Comma-Separated jQuery Performance with selector and context带有选择器和上下文的逗号分隔的 jQuery 性能
【发布时间】:2019-04-09 05:49:05
【问题描述】:

两者之间是否存在性能差异:

$("#divId :input")

$("#divId").find(":input")

$(":input", "#divId")

这里描述了最后一个变体https://api.jquery.com/jQuery/#jQuery-selector-context

(和Comma-separated jQuery selectors performance不太一样)

【问题讨论】:

  • 根据jQuery documentationInternally, selector context is implemented with the .find() method, so $( "span", this ) is equivalent to $( this ).find( "span" ). 根据this testfind() 看起来比后代选择器快。
  • 需要注意的是,children() 选项不保证是测试中前两个操作的 1:1 结果集。 @showdev
  • @showdev 非常有趣。谢谢。

标签: jquery performance


【解决方案1】:

以选择 id 开始的选择器是最快的,原因有两个:

  1. JQuery 使用本机方法来获取 id。
  2. 当您使用 id 作为选择器时,它会大大减少匹配(通常只会返回一个)。这意味着它只需要使用您的 ':input' 查询过滤一个(或几个元素)。越小匹配越快。

第一个和第二个选项之间的差异很小。

【讨论】:

  • 但是这三个不是都以 id 选择器开头吗?
  • @showdev 在上面指出 $(":input", "#divId") 相当于我不知道的 $("#divId").find(":input") 。请注意,这(显然)与 $(":input #divId") 不同
  • 忘记我的上一条评论,它们是一样的。
猜你喜欢
  • 2013-08-01
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 2016-04-24
  • 2019-01-22
相关资源
最近更新 更多