<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;
let old_style = {
height: '1vh',
width: '1vw',
color: 'red',
border: '1vmin solid red',
backgroundColor: 'black',
padding: '0.5vmin'
};
while (i < 10000) {
let style = el.getAttribute('style'), nu_style;
if( style == null || style == '' ) {
nu_style = JSON.stringify(old_style);
el.setAttribute('style', nu_style);
}
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 | 33.2 Ops/sec |
style.cssText | 58.6 Ops/sec |
style | 43.9 Ops/sec |
Object.assign | 20.6 Ops/sec |
setAttribute | 837.2 Ops/sec |
Let's break down the benchmark and explain what is being tested.
The benchmark is comparing four different ways to set CSS styles on an HTML element:
style.setProperty()
style.cssText
style
Object.assign()
with a custom style objectsetAttribute
(with null check)Options Compared:
setProperty()
method to set individual styles.cssText
property to set multiple styles in one string.style
property.Object.assign()
method to copy a custom style object into the element's style
property.Pros and Cons of Each Approach:
setProperty()
or cssText
, as individual properties must be separated.cssText
or direct assignment to style
, due to the need for copying and updating the object.Other Considerations:
setAttribute
, which can affect the performance of the test.vmin
and vw
units in the styles may impact the results, as these units are relative to the viewport size.Overall, this benchmark provides a comprehensive comparison of different methods for setting CSS styles on an HTML element, highlighting the trade-offs between precision, performance, and ease of use.