1. querySelector 与 getElementById
首先我们来比较 querySelector
与 getElementById
的差别,创建测试文件如下:
<!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
2. querySelectorAll 与 getElementByClassName
我们再创建一个测试文件来比较 querySelectorAll
与 getElementByClassName
,如下:
<!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
结论:
IE 差距大。
Chrome 对 querySelector
和 querySelectorAll
进行了优化,与传统方式差距很小。