jQuery选择器,效率 [英] jQuery Selectors, efficiency

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

问题描述

我最近一直在阅读不同选择器引擎的效率。我知道jQuery使用了Sizzle引擎和这个博客文章关于一些jQuery的东西提到Sizzle引擎会将你的选择器拆分成一个数组,然后从左到右解析。

I have been reading more lately about the efficiency of the different selector engines. I know that jQuery uses the Sizzle engine and this blog post about some jQuery stuff mentioned that the Sizzle engine will break apart your selector into an array then parse left to right.


然后,从右到左,开始用正则表达式解密每个项目。这也意味着选择器的最右侧部分应尽可能具体 - 例如,id或标签名称。

It then, from right to left, begins deciphering each item with regular expressions. What this also means is that the right-most part of your selector should be as specific as possible — for instance, an id or tag name.

我的问题是,使用 指定的ID或标签运行选择器是否更有效率名称:

My question is whether it is more efficient to run a selector with just the ID specified or the tag name as well:

var div = $('#someId');
//OR
var div = $('div#someId');

因为我在 div#someId 表单我倾向于以相同的方式做我的选择器,我是否导致Sizzle执行额外的工作(假设 QuerySelectorAll 不可用)?

Since I write my CSS in the div#someId form I tend to do my selectors the same way, am I causing Sizzle to perform extra work (assuming QuerySelectorAll is unavailable)?

推荐答案

jQuery和Sizzle优化 #id 选择器 [source] document.getElementById(id)。我认为他们无法使用标签#id 来优化它。

jQuery and Sizzle optimize the #id selector [source] to document.getElementById(id). I think they aren't able to optimize it like this with the tag#id.

第一个更快。

BTW指定 #id 选择器的标签名称过度指定,因为只有一个在文档上使用给定id的标记。过度指定的速度较慢甚至在CSS中

BTW specifying the tag name for an #id selector is over-specifying, as there can be only one tag with a given id on the document. Over-specifying is slower even in CSS.

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

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