<div id="test"></div>
el = document.getElementById("test");
let i = 0;
while (i < 10000) {
el.style.setProperty("color","red");
el.style.setProperty("border","1vmin solid red");
el.style.setProperty("padding","0.5vmin");
el.style.setProperty("background-color","black");
el.style.setProperty("height","1vh");
el.style.setProperty("width","1vw");
i++;
}
let i = 0;
while (i < 10000) {
el.style.cssText = "color:red;border:1vmin solid red;padding:0.5vmin;background-color:black;height:1vh;width:1vw;";
i++;
}
let i = 0;
while (i < 10000) {
el.style = "color:red;border:1vmin solid red;padding:0.5vmin;background-color:black;height:1vh;width:1vw;";
i++;
}
let style = {
height: '1vh',
width: '1vw',
color: 'red',
border: '1vmin solid red',
backgroundColor: 'black',
padding: '0.5vmin'
};
let i = 0;
while (i < 10000) {
Object.assign(el.style, style);
i++;
}
let i = 0;
while (i < 10000) {
el.setAttribute('style',"color:red;border:1vmin solid red;padding:0.5vmin;background-color:black;height:1vh;width:1vw;");
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
style.cssText | |
style | |
Object.assign | |
setAttribute |
Test name | Executions per second |
---|---|
style.setProperty | 13.7 Ops/sec |
style.cssText | 23.7 Ops/sec |
style | 20.1 Ops/sec |
Object.assign | 13.7 Ops/sec |
setAttribute | 22.1 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of six different approaches to setting CSS styles on an HTML element:
style.setProperty
style.cssText
style
(direct assignment)Object.assign
(assigning a style object)setAttribute
(setting the style
attribute)The benchmark uses JavaScript, specifically vanilla JavaScript, and is run on a Windows 7 desktop with Chrome 103.
Approaches Comparison
Here's a brief overview of each approach, their pros and cons, and other considerations:
setProperty
due to parsing and parsing limits in CSS.cssText
, can be less efficient due to parsing limitations.style
attribute)Library/Function Considerations
Object.assign()
method is a built-in JavaScript function used to copy properties from one object to another. It's widely supported and has good performance in modern browsers.Special JS Features/Syntax
There are no specific features or syntax mentioned in the benchmark code that require special attention.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
Keep in mind that these alternatives are not directly related to the six approaches tested in the benchmark.