<div id="test"></div>
el = document.getElementById("test");
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");
el.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;";
Object.assign(el.style, {
height: '1vh',
width: '1vw',
color: 'red',
border: '1vmin solid red',
backgroundColor: 'black',
padding: '0.5vmin'
});
el.setAttribute('style',"color:red;border:1vmin solid red;padding:0.5vmin;background-color:black;height:1vh;width:1vw;");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
style.cssText | |
style | |
Object.assign | |
setAttribute |
Test name | Executions per second |
---|---|
style.setProperty | 216320.3 Ops/sec |
style.cssText | 317483.4 Ops/sec |
style | 329686.4 Ops/sec |
Object.assign | 255346.8 Ops/sec |
setAttribute | 1727193.2 Ops/sec |
The provided JSON represents a JavaScript benchmarking test, specifically testing different methods for setting CSS properties on an HTML element.
Benchmarked Options:
style.setProperty()
style.cssText
style
objectObject.assign()
to set style propertiesstyle
attribute using setAttribute()
Comparison of Approaches:
style.setProperty()
is the fastest method, followed closely by direct assignment to the style
object and then by the other methods.style.setProperty()
allows for more fine-grained control over property names, values, and units. Direct assignment can be faster since it avoids the overhead of function calls and property name lookups.style.setProperty()
requires more code to set multiple properties, which might lead to slower initial execution times due to parsing and compilation. Direct assignment can be less readable for complex styles.style.cssText
is often considered the most readable option, as it clearly separates style declarations from other element properties.Object.assign()
offers flexibility in setting style properties, but its usage might make the code less readable.Library Usage:
The test uses the built-in style
property of HTML elements, which is not a library in itself. However, if you consider JavaScript engines or browsers as libraries, then they provide their own implementations of the style
API, including setProperty()
and other related methods.
Special JS Features/Syntax:
None are explicitly mentioned or used in this benchmark.
Alternatives:
custom-element
module, which offer more advanced styling options.Keep in mind that this benchmark focuses on the performance differences between various methods for setting CSS properties on an HTML element, rather than exploring alternative styling approaches.