<div id="foo" class="s"></div>
var element = document.getElementById("foo");
element.className += " bar bar2 bar3";
var element = document.getElementById("foo");
element.className = "bar bar2 bar3";
var element = document.getElementById("foo");
element.classList.add("bar");
element.classList.add("bar2");
element.classList.add("bar3");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
append | |
assign | |
classList |
Test name | Executions per second |
---|---|
append | 1722.3 Ops/sec |
assign | 7606874.0 Ops/sec |
classList | 1492572.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance of different approaches to manipulate the className
property of an HTML element in a web page.
Benchmark Definition JSON
The provided Benchmark Definition JSON contains three test cases:
className
property using the +=
operator.className
property directly using the assignment operator (=
).classList
API to add multiple classes to the element.Options Compared
The benchmark compares three different approaches:
+=
operator to append multiple classes.className
property directly using the assignment operator (=
).classList
API to add multiple classes.Pros and Cons of Each Approach
Here are some pros and cons of each approach:
className
property.Library Usage
None of the benchmark test cases use any external libraries, but they do rely on the document
object and the HTMLCollection
interface (which is built-in to JavaScript).
Special JS Features/Syntax
None of the provided test cases utilize any special JavaScript features or syntax. However, it's worth noting that some browsers may have slightly different behavior or optimizations for certain operations.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few:
class StringTemplate { static generate(className) { return
.${className}; } }; var classes = ['bar', 'bar2', 'bar3']; var classNameString = classes.map(cls => StringTemplate.generate(cls)).join(''); element.className += classNameString;
Keep in mind that while these alternatives might be interesting to explore, they may not necessarily offer significant performance benefits over the baseline approaches tested by MeasureThat.net.
Hope this explanation helps!