<div id="foo" class="test"></div>
var element = document.getElementById("foo");
element.className.indexOf("test")
element.classList.contains("test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 16230599.0 Ops/sec |
classList | 708135616.0 Ops/sec |
I'll break down the provided JSON data and explain what's being tested, compared, and its pros/cons.
Benchmark Definition
The benchmark is designed to compare the performance of two ways to check if an element has a specific class: className.indexOf
and classList.contains
.
Script Preparation Code
The script preparation code creates an HTML element with the ID "foo" and assigns it to the variable element
. The element also has a class attribute set to "test".
Html Preparation Code
The HTML preparation code generates a simple HTML structure with a div element that has the ID "foo" and the class "test".
Test Cases
There are two test cases:
element.className.indexOf("test")
. The indexOf
method returns the index of the first occurrence of the specified string within the string's characters. If no match is found, it returns -1.element.classList.contains("test")
. The contains
method returns a boolean value indicating whether the element has a specific class.Comparison
The benchmark compares the performance of these two approaches on the same set of HTML elements with the "test" class.
Pros and Cons:
classList.contains
because it searches for the substring, which can lead to slower performance.className.indexOf
.Library
There is no explicit library mentioned in the benchmark definition, but element.classList
uses the Web APIs introduced by HTML5. The classList
property provides a set of methods and properties to work with classes on elements.
Special JS Feature/Syntax:
The benchmark does not use any special JavaScript features or syntax beyond what's supported by standard Web APIs.
Alternatives
Other alternatives for checking class presence include:
getAttribute
method with the "class" attribute, e.g., element.getAttribute("class")
.includes
function.Keep in mind that these alternatives may have different performance characteristics and compatibility across browsers.