<div id="testElement" jsname="testElement"></div>
var el = document.getElementById('testElement');
var className = el.className;
var el = document.querySelector('#testElement');
var className = el.className;
var el = document.querySelector('[jsname="testElement"]');
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector | |
querySelector jsname |
Test name | Executions per second |
---|---|
getElementById | 3404800.0 Ops/sec |
querySelector | 1798661.0 Ops/sec |
querySelector jsname | 1478549.0 Ops/sec |
Let's break down the provided JSON and understand what is being tested in this JavaScript microbenchmark.
Benchmark Definition
The benchmark is designed to compare the performance of three different ways to retrieve an element from an HTML document:
getElementById
querySelector
querySelector
with a custom attribute (jsname
)Script Preparation Code and Html Preparation Code
The script preparation code is empty, which means that no initialization or setup code is required for the benchmark.
The HTML preparation code includes a simple <div>
element with an id
attribute set to "testElement"
and a jsname
attribute set to "testElement"
. This allows the benchmark to test the performance of each method on a single element.
Individual Test Cases
There are three individual test cases:
document.getElementById()
method to retrieve an element by its ID.document.querySelector()
method with a simple selector (just the #
symbol) to retrieve an element.document.querySelector()
method with a custom attribute (jsname
) to retrieve an element.Library Usage
None of the test cases use any external libraries.
Special JS Features or Syntax
The only special feature used in this benchmark is the jsname
attribute, which is not a standard HTML attribute. However, it's likely that the browser being tested supports this custom attribute.
Pros and Cons of Different Approaches
Here are some general pros and cons of each approach:
getElementById
, can use multiple selectors.Other Alternatives
Some alternative approaches that could have been used in this benchmark include:
getElementsByClassName()
instead of querySelector
querySelectorAll()
However, the choice of getElementById
, querySelector
, and querySelector jsname
likely aims to provide a simple and representative comparison of performance for these three methods.