<div id="test"></div>
el = document.getElementById("test");
style = el.style
attributeStyleMap = el.attributeStyleMap
style.setProperty("color","red");
style.setProperty("border","1vmin solid red");
style.setProperty("padding","0.5vmin");
style.setProperty("background-color","black");
style.setProperty("height","1vh");
style.setProperty("width","1vw");
style.cssText = "color:red;border:1vmin solid red;padding:0.5vmin;background-color:black;height:1vh;width:1vw;";
el.style = "color:red;border:1vmin solid red;padding:0.5vmin;background-color:black;height:1vh;width:1vw;";
attributeStyleMap.set("color","red");
attributeStyleMap.set("border","1vmin solid red");
attributeStyleMap.set("padding","0.5vmin");
attributeStyleMap.set("background-color","black");
attributeStyleMap.set("height","1vh");
attributeStyleMap.set("width","1vw");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
style.cssText | |
style | |
attributeStyleMap.set |
Test name | Executions per second |
---|---|
style.setProperty | 561854.1 Ops/sec |
style.cssText | 773526.1 Ops/sec |
style | 677138.8 Ops/sec |
attributeStyleMap.set | 205414.1 Ops/sec |
Let's dive into the benchmark.
Benchmark Purpose
The purpose of this benchmark is to compare the performance of four different approaches for setting CSS styles on an HTML element:
style.setProperty()
style.cssText
propertystyle
object (el.style = "...";
)attributeStyleMap.set()
method (introduced in modern browsers)Options Comparison
Here's a brief overview of each option and their pros and cons:
style.setProperty()
setProperty()
is the recommended way to set CSS properties in modern browsers. It allows you to specify a property value with a given priority (important) or without (non-important). This approach also provides better performance and is more efficient than using style.cssText
.
style.cssText
cssText
is an older property that allows setting CSS styles as a string value. However, this approach has significant drawbacks:
calc()
or var()
.style
object (el.style = "...";
)Assigning a string value directly to the style
object can lead to similar issues as using cssText
. It's not designed for complex styles or long strings and may result in performance problems due to parsing and tokenizing.
attributeStyleMap.set()
attributeStyleMap.set()
is a relatively new method for setting CSS properties on HTML elements. It provides an efficient way to update styles without modifying the style
object directly. However, its limited support means it may not be suitable for older browsers or environments that don't support this feature.
Library and Special Features
The benchmark uses the following libraries and special features:
attributeStyleMap
: a modern browser API introduced in recent versions of Chrome and Firefox.