jquery选择器速度

发布于 2024-08-07 01:03:18 字数 150 浏览 6 评论 0原文

这两个哪个更好/更快?

var a = $('.listItem', $('#myList'));

var a = $('#myList .listItem');

Which of these two is better/faster?

var a = $('.listItem', $('#myList'));

vs

var a = $('#myList .listItem');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

累赘 2024-08-14 01:03:18

首先,你以一种奇怪的方式错误做这件事。它应该是:

var a = $('.listItem', '#myList');

根据Resig<​​/a >,事实证明 find() 方法在大多数情况下是最快的:

var a = $("#myList").find(".listItem");

First of all, you're doing it wrong in a weird way. It should be:

var a = $('.listItem', '#myList');

And according to Resig, the find() method has proven to be quickest in most cases:

var a = $("#myList").find(".listItem");
走过海棠暮 2024-08-14 01:03:18

唯一真正了解的方法是对它们进行分析,这实际上是该问题的唯一答案。自 context 以来的第一次性能将会受到轻微影响当它是一个元素而不是一个 jQuery 对象时效果最好

The only real way to know is to profile them, that is really the only answer that can be given to the question. There will be a slight performance hit with the first since context works best when it is an element and not a jQuery object.

波浪屿的海角声 2024-08-14 01:03:18

第二个肯定更容易阅读,并且会使代码更容易维护。

...我认为这会让事情变得更好。

它们都应该产生相似的性能结果。

The second is definitely easier to read and would make the code easier to maintain.

...that in my opinion makes it better.

They should both produce similar performance results.

反差帅 2024-08-14 01:03:18

根据记录,

var a = $('.listItem',$('#myList'));

将执行完全相同的操作:

var a = $('#myList').find('.listItem');

在我的测试中,这是最快的

var a = $('#myList > .listItem');

哦,并且:

var a = $('.listItem', '#myList');

完全错误。(编辑)与第一个示例相同。


编辑:

我是个白痴。最后一个示例在功能方面与第一个示例完全相同。至于速度,我不好说。我的大胆猜测是,由于在第一个示例中,jQuery 对象已经具有选择器所需的元素,因此它会比仍需要查找元素的最后一个示例稍快一些。

For the record,

var a = $('.listItem',$('#myList'));

will perform exactly the same as:

var a = $('#myList').find('.listItem');

In my tests, this works the fastest:

var a = $('#myList > .listItem');

Oh, and:

var a = $('.listItem', '#myList');

is completely wrong. (edit) is the same as the first example.


EDIT:

I'm a moron. The last example is exactly the same as the first example in terms of functionality. As for speed, I can't say. My wild guess would be that since, in the first example, the jQuery object already has the elements asked for by the selector, it would be slightly faster than the last example that would still have to find the elements.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文