使用JS querySelector的性能

时间:2013-02-23 22:12:54

标签: javascript html dom

在网络浏览器中使用JavaScript时,以下内容之间存在任何性能差异:

现有的getElementById

document.getElementById("elem");

使用#id

查询选择器
document.querySelector("#elem");

使用[id = elem]

查询选择器
document.querySelector("[id=elem]");

我假设第一个将是最快的(只需要查找带有ID的元素)。最后一个看起来像是不好的做法。我喜欢第二个,因为使用querySelector可以使代码易于阅读。

有什么建议吗?

3 个答案:

答案 0 :(得分:17)

首先,

document.querySelector("#elem");

与document.getElementId不同,它有一个优点,它可以返回类。但是,由于它只返回具有该类名的第一个对象,所以它的用处远远减少了,因此如果您没有专门查找具有该类名的第一个对象,那么您也可以使用id。如果你使用,

document.querySelectorAll

但是,我相信(我可能错了),它将具有该类名的所有项目作为数组返回,其中常规querySelector等效于querySelectorAll [0]。另一个优点是,您可以通过它运行css3查询,这非常有用。

其次,

document.getElementById("elem");

与queryselector相比具有非常好的优势,因为它几乎快5倍,所以如果你坐在那里有几千行代码而你想优化所述代码,那么getElementById是要走的路。

最后,

document.querySelector("[id=elem]");

我个人认为在任何情况下都不需要使用它。如果你需要一个querySelector,为什么不使用#?这完全等同于你的第一个querySelector示例,但它有很多无用的字符。

编辑:总而言之,您可能最好使用document.getElementById。

答案 1 :(得分:3)

You can test it yourself。 getElementById是一种最快的方法

答案 2 :(得分:2)

  

是否有任何性能差异

可能,因为它们是不同的功能。 querySelector至少需要在检测到它等于getElementById之前解析选择器。我怀疑这种优化发生在属性选择器上,没有人使用它。所以我分享你的假设;和tests confirm them(感谢@Silver_Clash)。

我个人不喜欢第二个,因为使用动态id值更加模糊和可怕。明确使用getElementById只是更简洁。