<div id="test"></div>
element = document.getElementById("test");
let i = 0;
while (i < 10000) {
element.style.setProperty("--myVar", "blue");
i++;
}
let i = 0;
while (i < 10000) {
element.setAttribute("style", "--myVar: blue");
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
style.cssText |
Test name | Executions per second |
---|---|
style.setProperty | 192.9 Ops/sec |
style.cssText | 650.0 Ops/sec |
Let's break down the benchmark and explain what's being tested, along with the pros and cons of each approach.
Benchmark Overview
The benchmark compares two ways to set CSS styles on an HTML element:
style.setProperty
(Test Case 1)element.setAttribute("style", "...")
(Test Case 2)Options Compared
style.setProperty
: This method sets a CSS property named --myVar
with the value blue
. It's a more modern and efficient way to set CSS styles, as it allows for more precise control over the property name and value.element.setAttribute("style", "...")
: This method sets the style
attribute of an HTML element to a string containing the desired CSS properties. The format is property: value
, with multiple properties separated by semicolons.Pros and Cons
style.setProperty
:style
attribute.element.setAttribute("style", "...")
:style
attribute.Library/Utility
None mentioned in this benchmark.
Special JS Feature/Syntax
Other Considerations
When choosing between these two approaches, consider the trade-offs:
element.setAttribute("style", "...")
. This will ensure compatibility, but may impact performance.style.setProperty
. This method is more efficient and allows for better control over CSS styles.Alternatives
If you want to explore alternative approaches, consider:
element.style
: Setting CSS properties directly on the style
property of an element. While it's supported by all modern browsers, it may not be as efficient as style.setProperty
.Keep in mind that each approach has its own pros and cons, and the best choice depends on your specific use case, browser requirements, and performance considerations.