<div class="fus roh dah" id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var hasClass =(" "+element.className+" ").indexOf(" roh ") >= 0;
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var hasClass=element.classList.contains("roh");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 6317.1 Ops/sec |
classList | 622166.2 Ops/sec |
Let's break down the JavaScript microbenchmark at MeasureThat.net.
Benchmark Definition
The benchmark is designed to compare two approaches for checking if an HTML element has a specific class:
className
approach: This method uses the indexOf()
method to search for the presence of the class name "roh" in the element's className
property.classList
approach: This method uses the contains()
method provided by the classList
property, which is a part of the HTML5 API.Options Compared
The two approaches are compared in terms of their performance, specifically:
Pros and Cons of Each Approach
className
approach:classList.contains()
, especially for large class names or multiple classes with similar prefixes.indexOf()
method.classList
approach:classList
property.Library and Syntax
The benchmark uses no external libraries; it relies on native JavaScript methods. However, if you're interested in exploring alternative approaches using libraries or frameworks, here are some options:
contains()
method for checking if an object has a specific value.$()
function that can be used to check if an element has a specific class.No special JavaScript features or syntax are used in this benchmark.
Other Alternatives
If you're interested in exploring other approaches, consider the following alternatives:
indexOf()
.Keep in mind that these alternatives might introduce additional complexity, dependencies, or performance overhead.
Benchmark Preparation Code
The provided Html Preparation Code
generates an HTML element with the class "fus roh dah" and id "foo". The Script Preparation Code
is empty, which means the benchmark script will be executed directly in the browser context.
I hope this explanation helps you understand the JavaScript microbenchmark at MeasureThat.net!