在JQuery中查找节点的成本是多少? [英] What is the cost of finding a node in JQuery?

查看:65
本文介绍了在JQuery中查找节点的成本是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是保存 find()的结果,以避免多次子树遍历,如果我需要多次该值:

I always save the result of the find() in order to avoid multiple sub tree traversal if I need the value several times:

var $a_bar = $('div.foo').find('a.bar');
$a_bar.removeClass(...);
// ... code here
$a_bar.bazz();

而不是

$('div.foo').find('a.bar').removeClass(...);
// ... code here
$('div.foo').find('a.bar').bazz();

我想知道它是不是微优化......那么成本/复杂程度是多少在 JQuery中查找节点

I am wondering if it is not a micro-optimization... So what is the cost/complexity of finding a node in JQuery?

推荐答案

您可以在js perf: http://jsperf.com/
只需创建一个测试并运行它。

You can test it on js perf : http://jsperf.com/ Just create a test and run it.

我在这里创建了一个小测试: http://jsperf.com / jquery-find55

I have created a small test here : http://jsperf.com/jquery-find55

在我的浏览器上(firefox 18):

On my browser (firefox 18) :


  • 测试1(我保存查找结果)得分为7,074次操作第二次

  • 测试2(我不保存查找结果)得分为1,553次操作第二次

所以,是的,查找是慢,这绝对是一个好主意存储它在变量中。

So, yes, find is "slow" and it's definitively a good idea to store it in a variable.

这篇关于在JQuery中查找节点的成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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