<div class="foo"></div>
var i = 1;
var el = document.querySelector(".foo");
while (i--) {
window.getComputedStyle(el).color
}
var i = 1; var el = document.querySelector(".foo"); while (i--) { el.computedStyleMap().color }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getComputedStyle | |
computedStyleMap |
Test name | Executions per second |
---|---|
getComputedStyle | 2458942.8 Ops/sec |
computedStyleMap | 21672120.0 Ops/sec |
This benchmark compares two methods for retrieving the computed styles of an HTML element in the browser: getComputedStyle
and computedStyleMap
. The goal is to evaluate their performance and to understand the pros and cons of each approach.
The benchmark runs two tests:
getComputedStyle
: A traditional method to obtain the computed style of an element. The test executes this method in a loop to measure how many times it can retrieve the color property of an element with the class .foo
.
computedStyleMap
: A newer method that returns a CSSStyleValueMap
representing all computed CSS properties in a structured format. This also retrieves the color property but does so in a way that allows developers to access more detailed information about individual style properties.
The benchmark results indicate the performance of each method in terms of executions per second:
computedStyleMap
: 12,807,623 executions per secondgetComputedStyle
: 1,633,346.125 executions per secondThe numbers reveal that computedStyleMap
is significantly faster than getComputedStyle
in this specific test.
getComputedStyle
Pros:
Cons:
computedStyleMap
Pros:
Cons:
getComputedStyle
, requiring some ramp-up time to fully understand and adopt.When using either approach, consider the browser compatibility requirements for your project. While most modern browsers support computedStyleMap
, some older versions or niche browsers may only support getComputedStyle
. Additionally, while the performance advantage of computedStyleMap
is notable, profiling the actual performance improvements in the context of your specific application and use case is advised.
In addition to these methods, other alternatives for manipulating or reading computed styles could include:
style
property can provide immediate access to applied styles without needing to use either method.Overall, the choice between these methods ultimately depends on the performance requirements of your application and the specificities of the styles being manipulated.