<style>
.id {
background-color: var(--myVar);
}
</style>
<div id="test">Some content here</div>
element = document.getElementById("test");
let i = 0;
while (i < 10000) {
element.style.setProperty("--myVar", "blue");
element.style.setProperty("--myVar", "red");
i++;
}
let i = 0;
while (i < 10000) {
element.setAttribute("style", "--myVar: blue");
element.setAttribute("style", "--myVar: red");
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
style.setAttribute |
Test name | Executions per second |
---|---|
style.setProperty | 121.7 Ops/sec |
style.setAttribute | 95.6 Ops/sec |
I'll break down the provided benchmark definition and test cases to help you understand what's being tested.
Benchmark Definition: The benchmark definition represents a JavaScript microbenchmark that compares two approaches for setting a CSS property value on an HTML element:
setProperty
: Using the style.setProperty()
method.setAttribute
: Using the element.setAttribute()
method with a string containing the CSS property-value pair.Options Compared:
setProperty
vs setAttribute
The benchmark is testing which approach is faster and more efficient for setting a CSS property value on an HTML element, specifically when setting multiple values in a loop.
Pros and Cons of Each Approach:
setProperty
:var(--myVar)
).setAttribute
:var(--myVar)
).Library Usage:
The benchmark uses no external libraries. It relies solely on built-in JavaScript methods (style.setProperty()
and element.setAttribute()
) and DOM elements.
Special JS Features/Syntax:
None mentioned in this specific benchmark definition. However, it's worth noting that some modern browsers (e.g., Chrome) support CSS variables (e.g., var(--myVar)
), which might be relevant for other benchmarks or tests.
Other Alternatives:
element.style.cssText
).DOMTokenList
API (element.style.setProperty()
with tokenList
option).useStyle
hook).Keep in mind that this benchmark is focused on comparing two specific approaches, and other alternatives might be relevant for different use cases or requirements.