具有上下文的jQuery选择器的性能 [英] Performance of jQuery selector with context

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

问题描述

我正在阅读Brandon Aaron的这篇文章此处,关于jquery上下文可能如何提供帮助.所以我想到自己做一个测试.这就是我所做的.

I was reading this article by Brandon Aaron here, about how jquery context may help. So i thought of doing a test of my own. So this is what I did.

  1. 在先前创建的"#context"中创建了具有id ="context"的DIV,并嵌套了具有id ="holder"的DIV.

  1. Created a DIV with id="context" and nested DIV with id="holder" in "#context" created earlier.

创建了一个深度为18的嵌套DIV,并将<div id="context"><div id="holder"></div></div>附加到其上,从而生成了20个嵌套DIV.

Created a nested DIVs of depth 18 and append <div id="context"><div id="holder"></div></div> to it resulting in 20 nested DIVs

现在,我测试了通过以下选择器访问"#holder"所花费的时间:
一种. $("#holder") // no context
b. $("#holder", "#context") // with "#context" selector string
C. $("#holder", $("#context")) // sending jquery object each time with selector "#context"
d. $("#holder", $context) // where, var $context = $("#context"). Caching jquery obj
记录了每种访问X = 1000时间以及开始和结束时间差的情况.我发现花了以下时间:
case(a)是最不一致的28-32毫秒[jquery-1.3.2]
情况(b)+(c)的最高时间为60-65毫秒&分别为70-75毫秒
案例(d)的时间为40到50毫秒,带有1或2个尖峰值.

Now I tested time taken to access "#holder" via the following selectors:
a. $("#holder") // no context
b. $("#holder", "#context") // with "#context" selector string
c. $("#holder", $("#context")) // sending jquery object each time with selector "#context"
d. $("#holder", $context) // where, var $context = $("#context"). Caching jquery obj
Each of the cases where accessed X = 1000 times and start and end time difference was noted. I found that time taken for:
case(a) was the least consistent 28-32msec [jquery-1.3.2]
case(b)+(c) had the highest times 60-65 msec & 70-75 msec respectively
case(d) had 40-50msec with 1 or 2 spiked values.

这种基本检查有效吗?您可以在JSBIN的此处中使用JS代码. [让我知道我是否可以改善此测试的一些方法]
如果是,那么这个上下文"到底有什么帮助?

Is this type of basic check valid? You can play with the JS code here at JSBIN. [Do let me know If I can improve this test some how]
If YES, then how does this 'context' really help?


#注意:在jsbin编辑模式下还将jquery-1.3.2替换为jquery-1.4.2,您会惊讶地发现数字激增:P


#NOTE: also replace the jquery-1.3.2 with jquery-1.4.2 in jsbin edit mode and you'll be surprised to see the numbers bump up :P

推荐答案

当您要搜索更大的DOM时,上下文确实会有所帮助.搜索ID已经非常快,在这种情况下,上下文实际上并没有太大帮助.当您按标记名称或类别进行选择时,上下文真正起作用的地方.

Context really helps when you have a much larger DOM that you are searching through. Searching for IDs is already very fast and context doesn't really help that much in that case. Where context can really make a difference is when you are selecting by tag name or class.

尝试这样的测试: http://jsbin.com/aciji4/4

当您像这样增加DOM中的项目数量时,您确实可以看到上下文的时机变得更好: http ://jsbin.com/aciji4/6

you can really see the timing get better for context when you bump up number of items in the DOM like this: http://jsbin.com/aciji4/6

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

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