querySelector 与 getElementById 性能比较


1. querySelector 与 getElementById

首先我们来比较 querySelectorgetElementById 的差别,创建测试文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="test"></div>
    <script>
        console.time('querySelector');
        for (var i = 0; i < 100000; i++) {
            document.querySelector("#test");
        }
        console.timeEnd('querySelector');

        console.time('getElementById');
        for (var i = 0; i < 100000; i++) {
            document.getElementById("test");
        }
        console.timeEnd('getElementById');

    </script>
</body>
</html>

测试结果:IE11、Edge、Chrome

pic_39

2. querySelectorAll 与 getElementByClassName

我们再创建一个测试文件来比较 querySelectorAllgetElementByClassName,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <script>
        console.time('querySelectorAll');
        for (var i = 0; i < 10000; i++) {
          document.querySelectorAll(".test");
        }
        console.timeEnd('querySelectorAll');
        
        console.time('getElementsByClassName');
        for (var i = 0; i < 10000; i++) {
          document.getElementsByClassName("test");
        }
        console.timeEnd('getElementsByClassName');

    </script>
</body>
</html>

测试结果:IE11、Edge、Chrome

pic_40

结论:

IE 差距大。

Chrome 对 querySelectorquerySelectorAll 进行了优化,与传统方式差距很小。


文章作者: iKnow
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iKnow !
  目录