<div id="testElement"></div>
<div data-id="testElement"></div>
var el = document.getElementById('testElement');
var className = el.className;
var el = document.querySelector('[data-id=testElement]');
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector |
Test name | Executions per second |
---|---|
getElementById | 3616977.8 Ops/sec |
querySelector | 1675157.6 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark tests two ways to retrieve an element by its id
and then get its className
. The options being compared are:
document.getElementById('testElement')
: This is a traditional way of retrieving an element using its id
attribute. The method returns the first matching element in the DOM, or null
if no match is found.document.querySelector('[data-id=testElement]')
: This method uses CSS selectors to retrieve elements based on their attributes and classes. In this case, it's searching for an element with a data-id
attribute equal to "testElement"
.Pros and Cons:
document.getElementById('testElement')
:id
values.document.querySelector('[data-id=testElement]')
:id
-based retrieval, as it can also retrieve elements based on class names, attributes, and other CSS selectors. However, its performance might be slower due to the additional complexity of CSS selector evaluation.data-id
) and might have varying levels of browser support.Library usage: None in this benchmark.
Special JS features/syntax: The data-
prefix is used in the HTML attribute, which is a modern feature that allows developers to attach custom data attributes to elements. This is not specific to JavaScript but rather an HTML feature.
Now, let's discuss some alternatives:
document.querySelector('#testElement')
instead of document.getElementById('testElement')
: Although this method uses the same CSS selector syntax as the second test case, it would retrieve the first matching element in the DOM by its id
, rather than using a custom attribute.[class^='test']
or [data-attribute='custom-value']
, to see how they impact performance.Keep in mind that this benchmark specifically compares two traditional methods and the more modern querySelector
method. If you want to explore alternative approaches, feel free to create a new benchmark on MeasureThat.net!