<html>
<body>
<div class="foo" id="test2"></div>
<div class="foo2" id="test"></div>
</body>
</html>
document.querySelector(".foo");
document.getElementsByClassName('foo');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelector | 145677.2 Ops/sec |
getElementsByClassName | 3247940.5 Ops/sec |
Let's break down the provided benchmark.
What is tested?
The benchmark compares two DOM query methods: querySelector
and getElementsByClassName
. The test case uses HTML elements with both class attributes (e.g., .foo
) and IDs (e.g., test2
, test
). The goal is to measure the performance of these methods in retrieving elements from the document.
Options compared
Two options are compared:
querySelector
: This method is a part of the DOM Standard (ECMAScript 5) and allows selecting elements based on their class name, tag name, ID, or attribute values.getElementsByClassName
: This method is also part of the DOM Standard (ECMAScript 4) and retrieves all elements with a specified class name.Pros and cons
querySelector
:getElementsByClassName
:Library
In this benchmark, none of the libraries are explicitly mentioned. However, the use of querySelector
suggests that the browser supports ECMAScript 5 and its DOM Standard.
Special JS feature or syntax
The test case uses a CSS selector string in the querySelector
method (e.g., "document.querySelector(".foo")"
). This is a feature introduced in ECMAScript 5, allowing JavaScript to use CSS-like selectors for DOM querying. The getElementsByClassName
method also relies on this feature.
Other alternatives
If you want to test alternative methods for selecting elements, you could consider the following:
getElementsByTagName
: Retrieves all elements with a specified tag name (e.g., "document.getElementsByTagName('div')"
).querySelectorAll
: Similar to querySelector
, but returns an HTMLCollection that contains all matching elements.