<div id="foo"></div>
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
element.setAttribute("style", "width: "+i+"px; height: "+i+"px;");
}
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
element.style.cssText = `width: ${i}px; height: ${i}px;`;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute | |
style |
Test name | Executions per second |
---|---|
setAttribute | 98.3 Ops/sec |
style | 119.7 Ops/sec |
Measuring the performance of setting attribute and styling an element using CSS are two common scenarios that can be compared to understand which approach is faster.
Setting Attribute vs Styling with CSS
The two approaches being compared in this benchmark are:
style
attribute of the element directly. The syntax is element.setAttribute('style', 'width: ' + i + 'px; height: ' + i + 'px');
. This approach is more prone to browser quirks and inconsistencies because it relies on the browser's interpretation of the CSS syntax in the style
attribute.cssText
property of the element using a template literal. The syntax is element.style.cssText = 'width: ' + i + 'px; height: ' + i + 'px';
. This approach is more consistent and reliable because it follows the standard CSS syntax.Pros and Cons
setAttribute
due to the overhead of parsing and executing the CSS code.Library
There is no library being used in this benchmark. The JavaScript code is simple and does not involve any external libraries or frameworks.
Special JS Feature/Syntax
The test case uses a template literal feature in JavaScript, which allows you to embed expressions inside string literals using the backtick (`) character. This feature was introduced in ECMAScript 2015 (ES6) and has been widely adopted since then.
Other Alternatives
If you were to implement this benchmark yourself, you could consider other approaches such as:
However, these alternatives would likely introduce additional complexity and overhead, making them less suitable for a simple benchmarking scenario like this one.