jQuery选择器性能 [英] jQuery selector performance

查看:92
本文介绍了jQuery选择器性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我如何表达我的选择器,我的性能有巨大的变化。例如,看看这两个选择器,它们选择完全相同的元素:

  A)someTableRow.find(td.someColumnClass ).find(span.editMode)。find(input)
B)someTableRow.find(td.someColumnClass span.editMode input)
/ pre>

我希望B)更快,因为只有一个调用,但实际上我发现A)执行大约8倍。我不知道为什么,任何人有任何洞察力?感谢

解决方案

假设您至少使用jQuery 1.3(即添加Sizzle),您所看到的效果到DOM被遍历的改变。从此处


直到并包括jQuery 1.2.6
选择器引擎工作在自顶向下 b $ b(或从左到右)方式。 jQuery
1.3.x(即jQuery嵌入的 Sizzle )介绍了bottom up(或
right to left)方法查询
DOM。


你的第二个例子(td.someColumnClass span.editMode input),Sizzle有效地这样做:


  1. 每个都获得输入元素 someTableRow

  2. 元素遍历其原始树 span / code>。删除输入不具有这些祖先的元素

  3. 为每个 span.editMode 元素,通过 class =someColumnClass遍历 td 元素的祖先树。删除输入没有这些祖先的元素

然而,你每次调用 find()显式限定每个步骤,定义一个上下文并从中下移。您正在实施自上而下的方法。这相当于在每个步骤传递上下文,这是一般认为效果提升

  $('input',$ 'span.editMode',$('td.someColumnClass',someTableRow)))


I'm having huge variations in performance depending on how I express my selectors. For example, look at these 2 selectors, which select exactly the same elements:

A) someTableRow.find("td.someColumnClass").find("span.editMode").find("input")
B) someTableRow.find("td.someColumnClass span.editMode input")

I would expect to B) to be faster as there is only 1 call, but in fact I'm finding A) executes around 8 times faster. I have no idea why, anyone have any insight? Thanks

解决方案

Presuming you are using at least jQuery 1.3 (i.e. with the addition of Sizzle), the performance you are seeing is due to the change in which the DOM is traversed. From here:

Up to and including jQuery 1.2.6 the selector engine worked in a "top down" (or "left to right") manner. jQuery 1.3.x (ie, Sizzle, which jQuery embeds) introduced a "bottom up" (or "right to left") approach to querying the DOM.

In your second example ("td.someColumnClass span.editMode input"), Sizzle effectively does this:

  1. get all input elements inside someTableRow
  2. for each input element found, traverse its ancestor tree for span elements with class="editMode". Remove input elements that don't have these ancestors
  3. for each span.editMode element found, traverse its ancestor tree for td elements with class="someColumnClass". Remove input elements that don't have these ancestors

In your first example however, your are qualifying each step explicitly with each call to find(), defining a context and traversing down from there. You are enforcing the "top-down" approach. It is equivalent to passing in a context at each step, which is generally considered a performance booster:

$('input', $('span.editMode', $('td.someColumnClass', someTableRow)))

这篇关于jQuery选择器性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆