<style>
:root {
--test-color: 'red';
}
.test {
color: var(--test-color);
}
.test-blue {
--test-color: 'blue';
}
</style>
<div id="test"></div>
el = document.getElementById("test");
let i = 0;
while (i < 10000) {
el.style.setProperty("--test-color","blue");
i++;
}
let i = 0;
while (i < 10000) {
el.style.cssText = "--test-color:blue;";
i++;
}
let i = 0;
while (i < 10000) {
el.style = "--test-color:blue;";
i++;
}
let style = {
"--test-color": 'blue'
};
let i = 0;
while (i < 10000) {
Object.assign(el.style, style);
i++;
}
let i = 0;
while (i < 10000) {
el.setAttribute('style',"--test-color:blue;");
i++;
}
let i = 0;
while (i < 10000) {
el.classList.add('test-blue');
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style.setProperty | |
style.cssText | |
style | |
Object.assign | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
style.setProperty | 125.0 Ops/sec |
style.cssText | 109.2 Ops/sec |
style | 88.7 Ops/sec |
Object.assign | 434.8 Ops/sec |
setAttribute | 554.2 Ops/sec |
classList | 381.1 Ops/sec |
The benchmark outlined in the provided JSON is focused on testing various methods for updating CSS variable values within a web element in JavaScript. Specifically, it compares the performance of six different approaches:
style.setProperty
style.cssText
style
style.cssText
, but structured to assign the entire styles directly via an object format.cssText
, it will overwrite existing styles leading to potential loss of other applied styles.Object.assign
setAttribute
style
attribute of the element by assigning a complete style string.cssText
, it overwrites all existing styles, causing potential issues with previously assigned styles.classList
There are alternative approaches to managing styles in JavaScript. Using a CSS-in-JS library (like styled-components or Emotion) can manage styles dynamically and maintain performance while providing a structured way to manage style definitions. These libraries often leverage JavaScript's flexibility to handle styles more declaratively than traditional DOM manipulation methods.
In the benchmark results, setAttribute
performed the best in terms of execution speed, followed by classList
and Object.assign
. The style.setProperty
, style.cssText
, and style
methods were notably slower, possibly due to the overhead of DOM manipulation involved with those methods.
This benchmark serves as a comparison guide for developers to choose the best approach for updating CSS variables in applications, highlighting performance considerations as well as the context of use for each method. Evaluating these pros and cons will help engineers decide which technique suits their specific requirements best, considering maintainability and performance.