28

在 Web 浏览器中使用 JavaScript 时,以下各项之间是否存在任何性能差异:

现有的 getElementById

document.getElementById("elem");

使用#id 查询选择器

document.querySelector("#elem");

使用 [id=elem] 查询选择器

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

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

有什么建议么?

4

3 回答 3

18

首先,

document.querySelector("#elem");

与 document.getElementId 不同,它有一个优势,它可以返回类。但是,由于它只返回具有该类名的第一个对象,因此它的实用性大大降低,因此如果您不是专门寻找具有该类名的第一个对象,则最好只使用一个 id。如果你使用,

document.querySelectorAll

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

第二,

document.getElementById("elem");

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

Lastly,

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

I, personally, don't see the need to use this in any situation. If you needed a querySelector, why not just use a # ? This is exactly equivalent to your first example of querySelector, however it has a lot of useless charaters.

Edit: Just to be clear, in summary, you're probably better off using document.getElementById.

于 2013-02-23T22:25:32.627 回答
5

你可以自己测试一下。getElementById 是最快的方法

于 2013-02-23T22:25:19.607 回答
3

is there any performance difference

Probably, since they are different functions. querySelector at least needs to parse the selector before detecting that it's equal to getElementById. And I doubt this optimisation takes place for the attribute selector at all, no one uses it. So I share your assumptions; and tests confirm them (thanks to @Silver_Clash).

Personally I do not like the second one, as it is more ambiguous and awful to use with dynamic id values. Explicitly using getElementById is just more concise.

于 2013-02-23T22:26:56.190 回答