<style type="text/css">
.hide {
display: none;
}
</style>
<div id="foo"></div>
var element = document.getElementById("foo");
var i = 3000;
while (i--) {
element.classList.toggle("hide" , false);
}
var element = document.getElementById("foo");
var i = 3000;
while (i--) {
element.classList.remove("hide");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList toggle | |
classList add hide |
Test name | Executions per second |
---|---|
classList toggle | 3618.5 Ops/sec |
classList add hide | 2366.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark consists of two individual test cases, each measuring the performance difference between two approaches: classList.toggle(false)
and classList.remove('hide')
.
Options Compared
The benchmark compares the performance of two different options:
classList.toggle('hide', false)
: This method toggles the presence of a class with the value 'hide'
, setting it to false
.classList.remove('hide')
: This method removes a class with the value 'hide'
.Pros and Cons
Both methods have their pros and cons:
classList.toggle('hide', false)
:classList.remove('hide')
:Library and Purpose
In both test cases, the Element.classList
API is used. This API provides methods for managing classes on an element:
classList
: returns the HTMLStyleRuleList
object containing all classes defined on an element.toggle(class_name, force)
(in this case): adds or removes a class with the specified value, depending on the second parameter (force = false
).remove(class_name)
: removes a class with the specified value.Special JS Feature
There is no special JavaScript feature or syntax being tested in this benchmark. The focus is solely on comparing the performance of two different class management approaches.
Other Alternatives
For those interested, here are some alternative approaches for managing classes:
getAttribute()
and setAttribute()
: Using these methods to set and remove attributes can be an alternative approach, but it's generally less efficient than using the classList
API.style.display = 'none'
: This method sets the display
property to 'none'
, effectively hiding an element without removing a class.Keep in mind that these alternatives may have different performance characteristics and are not necessarily more efficient or readable than the classList
API approaches being tested.