<div id="foo" class="bar test space OK"></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();
}
let element = document.getElementById("foo");
let i = 1000;
while (i--) {
const classes = element.className.split(/\s+/g)
if (classes.length) {
let selector = `${classes.join('.')}`;
if (selector.endsWith('.')) {
selector = `.${selector.slice(0, -1)}`;
}
}
}
let element = document.getElementById("foo");
let i = 1000;
while (i--) {
let selector = "." + element.className.trim().replace(/\s+/g, '.');
}
let element = document.getElementById("foo");
let i = 1000;
while (i--) {
let selector = "." + element.className.replace(/\s+/g, '.');
if (selector.endsWith('.')) {
selector = selector.slice(0, -1);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Split + filter Classname | |
Trim + replace ClassName | |
No Trim - Replace CLassName |
Test name | Executions per second |
---|---|
Split + filter Classname | 5821.8 Ops/sec |
Trim + replace ClassName | 9503.6 Ops/sec |
No Trim - Replace CLassName | 7192.6 Ops/sec |
The benchmark defined in the provided JSON file compares three different JavaScript approaches for handling and manipulating class names from a DOM element (<div id="foo" class="bar test space OK"></div>
). The aim is to evaluate the performance of each approach by measuring the number of executions per second.
Split + filter Classname
split
allows precise control over how classes are interpreted.Trim + Replace ClassName
No Trim - Replace ClassName
The performance of the three approaches was tested on a specific setup and resulted in the following executions per second:
When selecting one of these approaches for practical application, consider the context in which it will be used:
Besides the provided benchmarks, alternative methods could include:
classList
: Modern JavaScript offers the classList
API, which provides methods like add
, remove
, and toggle
, abstracting away the need for manual string manipulation and providing a cleaner interface.In conclusion, this benchmark serves to highlight the trade-offs between performance and clarity in different JavaScript strategies for manipulating class names and invites consideration of the best fit based on specific application needs.