<div class="wrapper">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
document.querySelector(".item");
document.getElementsByClassName("test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
queryselector | |
class by name |
Test name | Executions per second |
---|---|
queryselector | 4989222.0 Ops/sec |
class by name | 4411249.5 Ops/sec |
What is being tested?
The provided JSON represents two microbenchmarks that test the performance of JavaScript's getElementsByClass
and querySelector
methods.
Options compared:
Two options are being compared:
document.querySelector(".item")
: This method uses a CSS selector to select elements with the class "item" by value.document.getElementsByClassName("test")
: This method returns an HTMLCollection of elements with the exact class name "test".Pros and Cons:
document.querySelector(".item")
:.item span
, .item .inner
).document.getElementsByClassName("test")
:Library usage:
Neither benchmark uses a specific library, but querySelector
relies on the W3C CSS Selectors API, which is widely supported in modern browsers. getElementsByClass
, on the other hand, is a proprietary method provided by Internet Explorer and its clones (e.g., Firefox, Chrome).
Special JS features or syntax:
Neither benchmark uses any special JavaScript features or syntax beyond standard ES5/ES6 syntax.
Other alternatives:
For faster and more flexible DOM querying:
document.querySelectorAll(".item")
: This method returns a NodeList of elements matching the specified CSS selector.Element.prototype.querySelector
and Element.prototype.querySelectorAll
: These methods, introduced in ECMAScript 2015 (ES6), provide a modern alternative to querySelector
and getElementsByClassName
.For performance-critical applications:
Keep in mind that the best approach depends on your specific use case, target browsers, and performance requirements.