jquery的性能可见 [英] Performance of jquery visible

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

问题描述

我在页面上有一堆复选框,我一次只显示这些复选框的子集。

I have a bunch of checkboxes on a page, and I only show a subset of those checkboxes at a time.

然后执行一些循环遍历所有操作的操作复选框,看看是否被选中:

I then perform some action which loops through all of the checkboxes and sees if they are checked or not:

例如

$(".delete_items").click( function() {
     $('.checkboxes' ).each(function(){
     //do stuff
     }
}

然后我在思考,因为用户永远不会与隐藏的复选框进行交互,添加:对复选框可见会加快循环

Then I was thinking, well since the user can never interact with the hidden checkboxes, that adding :visible to checkboxes would speed up the loop

例如

$(".delete_items").click( function() {
     $('.checkboxes :visible' ).each(function(){
     //do stuff
     }
}

但我不知道是否添加:可见会增加更多开销。有什么想法吗?

But I don't know if adding :visible adds more overhead. Any thoughts?

推荐答案

:visible 将添加肯定更多的开销,因为jQuery必须检查几个属性元素是否可见:

:visible will add for sure more overhead, as jQuery has to check several properties whether an element is visible or not:


可以将元素视为隐藏的原因有以下几种:

Elements can be considered hidden for several reasons:


  • CSS显示值为none。

  • 它们是type =hidden的表单元素。

  • 它们的宽度和高度显式设置为0.

  • 祖先元素被隐藏,所以该元素未显示在页面上。

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

来源 - :hidden Selector | jQuery API文档

特别是最后一点似乎意味着为每个增加开销的元素遍历DOM。

Especially the last point seems to imply traversing the DOM up for every element which adds overhead.

如果你只是使用类作为选择器,jQuery可以使用浏览器函数,如 getElementsByClass querySelectorAll

If you just use the class as selector, jQuery can make use of browser functions like getElementsByClass or querySelectorAll.

另一方面,如果您对这些复选框执行计算复杂操作,则循环使用较少的复选框可能会超过之前的查找。

On the other side, if you perform computational complex actions on these checkboxes, looping over fewer of them might outweigh the previous lookup.

你必须自己做基准测试。

You definitely have to benchmark it yourself.

更新:

另一个想法是将另一个类分配给可见复选框并选择它们

Another idea to assign another class to the visible checkboxes and select them with

$('.checkboxes.otherClass')

绝对应该比使用<$ c $更快C>:可见。

更新2:

我创建了一个jsPerf: http://jsperf.com/jquery-visible-test

I created a jsPerf: http://jsperf.com/jquery-visible-test

它可能不是最好的测试用例,但至少对我来说(Chrome 8,Mac OS X 10.6),使用:可见慢约45%(甚至更糟糕的是Firefox 3.6.13:慢了75%。

It might not be the best test case but, at least for me (Chrome 8, Mac OS X 10.6), using :visible is ~45% slower (even worse in Firefox 3.6.13: ~75% slower).

更新3:

使用两个类似乎更快,我更新了测试用例。

Using two classes seems to be even faster, I updated the test case.

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

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