<div class="foo"></div>
var i = 1;
var el = document.querySelector(".foo");
while (i--) {
window.getComputedStyle(el).getPropertyValue('color')
}
var i = 1; var el = document.querySelector(".foo"); while (i--) { el.computedStyleMap().get('color') }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
computedStyleMap |
Test name | Executions per second |
---|---|
getComputedStyle | 1291693.4 Ops/sec |
computedStyleMap | 1441801.2 Ops/sec |
The benchmark under discussion compares two methods for obtaining the computed styles of a DOM element in JavaScript: getComputedStyle
and computedStyleMap
.
CSSStyleDeclaration
object representing the specified element's computed style. The benchmark executes this method in a loop to check how many times the style can be retrieved per second.CSSStyleValueMap
object. This object allows access to the properties of an element’s computed styles in a more structured manner and is designed for direct manipulation of styles.getComputedStyle
CSSStyleDeclaration
object, which may introduce overhead if repeatedly accessed in a performance-sensitive loop.computedStyleMap
When evaluating these two methods, developers should consider the following:
Performance: computedStyleMap
shows superior performance in this benchmark, executing more times per second compared to getComputedStyle
. This suggests that for applications needing to efficiently read computed style values in high-frequency situations (like animation), computedStyleMap
may be advantageous.
Browser Support: Before deciding on which method to implement in production code, it is crucial to check compatibility across target browsers to ensure the method used won't lead to functionality issues in some users' environments.
Inline Styles: Instead of querying computed styles, modifying styles directly through inline styles (using style
attribute) can improve performance, although this does not reflect final computed styles that come from various sources (like CSS files).
CSS Variables (Custom Properties): Utilizing CSS variables could mitigate the need for computed styles retrieval when dynamic styling is used, as their values can be read and modified directly.
Mutation Observers: In scenarios where styles change over time and require tracking, using Mutation Observers can help respond to changes without repeatedly querying for computed styles.
This benchmark offers insights into the performance characteristics of two distinct approaches for styling retrieval in JavaScript, aiding developers in making informed choices based on their application's needs and the environments they target.