<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.style.postiion = "fixed";
}
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 style | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
direct style | 50252.2 Ops/sec |
setAttribute | 3734.5 Ops/sec |
classList | 3678.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and their pros and cons.
What is being tested?
The benchmark tests three different ways to set the position
property of an HTML element in JavaScript:
style
property directly on the element.setAttribute
method.classList
API to add a class with the desired value.What options are being compared?
The three options are being compared in terms of their performance, specifically how many executions per second (ExecutionsPerSecond) they produce.
Pros and Cons:
Library/ Framework Consideration
The classList
API is a modern JavaScript feature that provides an efficient way to work with classes on HTML elements. It's supported by most modern browsers and frameworks, making it a good choice for performance-critical applications.
Special JS Feature/Syntax
None of the benchmarked code uses special JavaScript features or syntax beyond standard ES6+ syntax.
Other Alternatives
For setting the position
property directly on an element:
style.position
property with the inline-style
CSS rule (although this is less efficient than direct style)These alternatives may incur additional overhead or require more complex setup, making them less suitable for performance-critical applications.
Benchmark Preparation Code
The provided HTML preparation code <div id="foo"></div>
creates an empty div
element with the ID "foo", which is used as a target for the benchmarking tests.
For the script preparation code, each test case is identical and only sets up the initial conditions for the test:
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
// The actual code being tested is inside this loop
}
This code creates a reference to the div
element with ID "foo" and initializes a counter variable i
. The test then runs in a loop, executing the code inside it repeatedly.