<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="el" class="test"></div>
$("#el").hasClass("test");
document.getElementById("el").classList.contains("test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery hasClass | |
Vanilla JS classList.contains |
Test name | Executions per second |
---|---|
jQuery hasClass | 702160.1 Ops/sec |
Vanilla JS classList.contains | 4021423.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The test compares the performance of two approaches: using jQuery's hasClass
method and vanilla JavaScript's classList.contains
method to check if an element has a certain class.
Options Compared
Two options are compared:
hasClass
method: This method is part of the jQuery library, which provides a convenient way to manipulate HTML documents, events, and DOM elements.classList.contains
method: This method is part of the ECMAScript Standardized Specification, introduced in modern browsers (from around 2016 onwards), and allows direct access to an element's class list.Pros and Cons
hasClass
method:classList.contains
method:Library (jQuery)
jQuery is a popular JavaScript library that simplifies DOM manipulation, event handling, and Ajax interactions. It provides an easy-to-use API for selecting elements, event handling, and manipulating the DOM. In this benchmark, jQuery's hasClass
method is used to check if an element has a certain class.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark. Both approaches rely on standard JavaScript functionality.
Benchmark Preparation Code
The HTML preparation code includes a link to the jQuery library (version 3.2.1) and creates a simple <div>
element with an ID of "el" and a class of "test".
Test Cases
Two test cases are defined:
hasClass
method to check if the element with ID "el" has the class "test".classList.contains
method to achieve the same result.Latest Benchmark Result
The latest benchmark results show that Opera Mobile 64 (a mobile browser) performs better with the vanilla JavaScript approach, executing approximately 1156166 tests per second, compared to around 308651 tests per second for jQuery. However, this difference might not be significant in all scenarios, and other factors like system resources, network conditions, or specific hardware configurations can impact performance.
Other Alternatives
For similar benchmarks, you may want to explore:
classList
API (e.g., using the ElementMasks
API)CSSClassList
API)Keep in mind that these alternatives may have different performance characteristics, ease of use, and compatibility with various browsers and environments.