<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.style.postiion = "fixed";
element.style.bottom = "0";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
direct styles | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
direct styles | 3030.6 Ops/sec |
setAttribute | 14494.9 Ops/sec |
classList | 7917.4 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three different approaches to apply CSS styles to an HTML element:
var element.style.postiion = "fixed";
)var element.setAttribute("class", "bar");
)classList
API (element.classList.add("bar");
)Options Comparison
The three approaches are compared in terms of performance, specifically the number of executions per second.
style
property of the element. While it's a straightforward way to apply styles, it can be slower due to the need to access and modify the element's CSS rules.setAttribute()
method to set a CSS class on the element. While it's widely supported, setting attributes can be slower than directly manipulating style properties.classList
API: The classList
API provides a more modern and efficient way to manage CSS classes on elements. It's generally faster than setting attributes or direct style assignment.Pros and Cons
Here are some pros and cons of each approach:
classList
API:Library/Functionality
None of the benchmark's test cases use any external libraries or functions beyond basic JavaScript.
Special JS Features/Syntax
The benchmark uses some special features of JavaScript, including:
var element.style.postiion = "fixed";
line uses a template literal to construct a string.let
keyword and arrow functions, although these are not explicitly required by the benchmark.Other Alternatives
Some alternative approaches that could be used in this benchmark include:
:nth-child()
pseudo-class or other CSS selectors.Keep in mind that these alternatives would likely change the nature of the benchmark and may not be as relevant to the specific question being asked.