<div id="foo"></div>
var element = document.getElementById("foo");
const array = new Array(10000);
for (var i = 0; i < array.length; i++) {
array[i] = `width: ${i}px; height: ${i}px;`
}
for (var i = 0; i < array.length; i++) {
element.setAttribute("style", array[i]);
}
for (var i = 0; i < array.length; i++) {
element.style.cssText = array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute | |
style |
Test name | Executions per second |
---|---|
setAttribute | 311.7 Ops/sec |
style | 336.2 Ops/sec |
The provided benchmark is designed to compare two methods for applying CSS styles to a DOM element in JavaScript: using the setAttribute()
method and directly setting the style.cssText
property. Here’s a breakdown of what is being tested, the differences between the methods, and considerations for each approach.
setAttribute Method
for (var i = 0; i < array.length; i++) {
element.setAttribute("style", array[i]);
}
setAttribute()
function, which sets the value of the specified attribute (in this case, "style") on the DOM element.style.cssText Property
for (var i = 0; i < array.length; i++) {
element.style.cssText = array[i];
}
cssText
property of the element's style
object.Pros:
Cons:
setAttribute
is typically slower than direct property access, especially when called repeatedly in a loop, because it may involve more overhead as it parses the attribute string.Pros:
Cons:
setAttribute
in terms of general attribute manipulation; it can only be used for CSS styles.When choosing between these two methods, performance is a crucial factor, particularly in cases where styles are changed frequently, such as within animations or user interactions. The results indicate that the style.cssText
approach performed better in this benchmark, achieving more executions per second compared to setAttribute
.
This benchmark serves as a practical example for developers, illustrating the real-world impact of these two methods on performance.
Other alternatives for applying styles to elements in JavaScript include:
Individual Style Properties: Instead of setting the whole string, styles can be applied by setting individual properties on the style
object, e.g., element.style.width = '100px'; element.style.height = '100px';
. This can be even more performant in scenarios where you are changing a few styles without needing to reconstruct the entire style string.
CSS Classes: Instead of inline styles, one could add or remove classes from the element, managing styles through CSS classes rather than JavaScript. This is generally more performant and makes the code cleaner and easier to maintain, as styles are kept separate from the JavaScript logic.
By understanding these techniques and their respective trade-offs, developers can make informed decisions about how to manipulate styles and optimize their application's performance.