【问题标题】:Jquery: select.children[index] faster than nth-child selector?Jquery:select.children[index] 比 nth-child 选择器快?
【发布时间】:2011-12-01 22:29:16
【问题描述】:

在 jquery 中,假设我有一个 html 选择器 select。从选择器中获取第 i 个元素哪个更快?如果一个更快,那么快多少?少一点还是多一点?

select.children[i]

或者

$j('*:nth-child(' + i + ')', select)

【问题讨论】:

  • 我可以建议访问JS Perf 吗?它可以让你很容易地对 JavaScript 的性能进行基准测试。
  • 好吧,你为什么不计时呢?

标签: jquery jquery-selectors css-selectors


【解决方案1】:

select.children[i] 更快。这是因为它没有 jQuery 的开销。这是jsPerf,您可以在其中查看结果。

对于我使用的第一个测试

var select = document.getElementById('select'); 
var option = select.children[2]; 

第二个

var select = document.getElementById('select'); 
var option = $('*:nth-child(' + 2 + ')', select); 

【讨论】:

  • 即使两者都使用 jQuery,索引方法 (select.children()[i]) 的速度也快两倍。
  • 真的吗?我得到了一些矛盾的结果,请查看更新的 jsperf 我添加了更多测试。
  • 刚刚运行你的性能(Fx 8),$...children()[i] 实际上比nth-child 变体快大约三倍。我的表现只有大约两倍:jsperf.com/index-or-n-th-child-jquery
猜你喜欢
  • 2013-04-04
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
相关资源
最近更新 更多