选择多个项目时的 jQuery 性能
这更多的是一个好奇的问题。当执行以下操作时:
$('.selector1, .selector2').doSomething()
jQuery 是否完全遍历 DOM 两次以获取与每个选择器匹配的每一组对象,还是在一次遍历 DOM 中找到所有元素?
This is more of a curiosity question. When doing the following:
$('.selector1, .selector2').doSomething()
Does jQuery fully traverse the DOM twice to get each set of objects matching each selector or is it finding all the elements in one traversal of the DOM?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为它使用本机浏览器功能来找到它,使用:
I think it uses the native browser functions to find this, using:
这实际上取决于浏览器。在较新的浏览器中,它将使用 document.querySelectorAll 进行任何 DOM 查询(在幕后为类调用 document.getElementsByClassName)。在不支持这一点的旧浏览器中,它必须自己解决,这显然会更慢。
一般来说,您应该更喜欢首先通过 id 查找内容(或者至少缩小范围)。为了速度,类和标签名称将是下一个。基本上,原生支持的 DOM 操作是最好的。
It really depends on the browser. In newer browsers, it will use document.querySelectorAll for any DOM queries (under the hood this calls document.getElementsByClassName for classes). In older browsers that don't support this, then it has to figure it out on its own, which will obviously be slower.
In general, you should prefer to find stuff by id first (or at least narrow the scope). Class and tag names would be next for speed. Basically, the natively supported DOM operations are best.