<div id="variableContainerSso"></div>
/*your preparation JavaScript code goes here
To execute async code during the script preparation, wrap it as function globalMeasureThatScriptPrepareFunction, example:*/
async function globalMeasureThatScriptPrepareFunction() {
// This function is optional, feel free to remove it.
// await someThing();
}
document.querySelector("div[id^='variableContainerSso']")
document.querySelector("div[id='variableContainerSso']")
document.querySelector("#variableContainerSso")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
beginning with attribute selector | |
attribute selector | |
id selector |
Test name | Executions per second |
---|---|
beginning with attribute selector | 8773790.0 Ops/sec |
attribute selector | 8989975.0 Ops/sec |
id selector | 9232063.0 Ops/sec |
The benchmark provided tests the performance of different CSS selector methods in JavaScript for querying an HTML element. The focus is on how effectively and efficiently various selectors retrieve a div
element with a specific ID.
ID Selector (#variableContainerSso
):
document.querySelector("#variableContainerSso")
Attribute Selector (div[id='variableContainerSso']
):
document.querySelector("div[id='variableContainerSso']")
div
element by specifying an exact match for the id
attribute. While generally fast, attribute selectors may involve more overhead than ID selectors due to additional checks.Beginning with Attribute Selector (div[id^='variableContainerSso']
):
document.querySelector("div[id^='variableContainerSso']")
div
elements whose id
attribute starts with 'variableContainerSso'. This is less efficient than the exact ID match as it requires examining the value's prefix before determining a match.The results are expressed in terms of ExecutionsPerSecond
, which indicates how many times each selector could successfully execute within one second:
ID Selector (#variableContainerSso
):
Attribute Selector (div[id='variableContainerSso']
):
Beginning with Attribute Selector (div[id^='variableContainerSso']
):
The performance of these selectors can vary depending on the browser's implementation and the complexity of the DOM structure. While the benchmark details provided are for Chrome (version 132), performance characteristics might differ across other browsers or versions.
Other alternatives could include:
getElementsByClassName
or getElementsByTagName
when the query context allows for broader selections.In conclusion, this benchmark demonstrates the importance of understanding selector performance in JavaScript, particularly when optimizing applications or manipulating the DOM frequently. Having the right tool for the job can lead to significant improvements in performance and user experience.