jquery选择器速度
这两个哪个更好/更快?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,你以一种奇怪的方式
错误做这件事。它应该是:根据Resig</a >,事实证明
find()
方法在大多数情况下是最快的:First of all, you're doing it
wrongin a weird way. It should be:And according to Resig, the
find()
method has proven to be quickest in most cases:唯一真正了解的方法是对它们进行分析,这实际上是该问题的唯一答案。自 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.
第二个肯定更容易阅读,并且会使代码更容易维护。
...我认为这会让事情变得更好。
它们都应该产生相似的性能结果。
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.
根据记录,
将执行完全相同的操作:
在我的测试中,这是最快的:
哦,并且:
完全错误。(编辑)与第一个示例相同。编辑:
我是个白痴。最后一个示例在功能方面与第一个示例完全相同。至于速度,我不好说。我的大胆猜测是,由于在第一个示例中,jQuery 对象已经具有选择器所需的元素,因此它会比仍需要查找元素的最后一个示例稍快一些。
For the record,
will perform exactly the same as:
In my tests, this works the fastest:
Oh, and:
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.