<div id="element" style="background:#555;color:#FFF;position:absolute;left:0;top:0;width:400px;height:100px;">
</div>
var elem = document.getElementById('element');
for (var i = 0; i< 1000 ; i++){
elem.style.width = i + 'px';
elem.style.height = i + 'px';
elem.style.top = i + 'px';
elem.style.left = i + 'px';
}
for (var i = 0; i< 1000 ; i++){
elem.style['width'] = i + 'px';
elem.style['height'] = i + 'px';
elem.style['top'] = i + 'px';
elem.style['left'] = i + 'px';
}
for (var i = 0; i< 1000 ; i++){
elem.setAttribute('style','width:' + i + 'px;height:' + i + 'px;top:' + i + 'px;left:' + i + 'px;');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
style by property | |
style by name | |
setAttribute |
Test name | Executions per second |
---|---|
style by property | 118.6 Ops/sec |
style by name | 123.3 Ops/sec |
setAttribute | 154.1 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance difference between three approaches to set CSS styles on an HTML element: setting individual properties, using the style
attribute with dot notation (e.g., elem.style.width = ...
), and using the setAttribute
method.
Approaches Compared
elem.style.width = i + 'px';
.style by property
): This approach uses the style
attribute with dot notation to set multiple styles at once, e.g., elem.style['width'] = i + 'px';
.setAttribute
method: This approach sets the entire CSS style string as an attribute value using the setAttribute
method, e.g., elem.setAttribute('style', 'width:' + i + 'px;height:' + i + 'px;top:' + i + 'px;left:' + i + 'px;');
.Pros and Cons
style by property
)style
attribute's syntax.setAttribute
method:Library and Special JS Features
There is no explicit library mentioned in the benchmark. However, the use of document.getElementById
and setAttribute
suggests that this benchmark is running on a modern JavaScript environment that supports these features.
No special JavaScript features or syntax are used in this benchmark, apart from the let
keyword (not shown) which is assumed to be present since it's not explicitly mentioned as a test case.
Other Alternatives
In addition to the three approaches tested here, other alternatives for setting CSS styles on an element include:
css
module in Node.js or the style
attribute with the css
property in browser environments (e.g., Chrome DevTools).Keep in mind that these alternatives might have their own trade-offs in terms of performance, readability, and maintainability.