<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<div id="el"></div>
document.getElementById("el").classList.remove("test");
$("#el").addClass("test");
document.getElementById("el").classList.add("test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery addClass | |
Javascript classList.add |
Test name | Executions per second |
---|---|
jQuery addClass | 551906.8 Ops/sec |
Javascript classList.add | 782735.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance difference between two approaches: jQuery's addClass
method and the native JavaScript classList.add
method. The test is designed to manipulate an HTML element (<div id="el">
) by removing a class ("test"
), and then adding a new class using each of the two methods.
Options Compared
The benchmark compares the following options:
addClass
: This method adds a CSS class to an element, similar to classList.add
in native JavaScript.classList.add
: This method also adds a CSS class to an element, but without the additional overhead of jQuery.Pros and Cons
jQuery's addClass
:
Pros:
Cons:
Native JavaScript classList.add
:
Pros:
Cons:
Other Considerations
The benchmark also considers the device platform, operating system, and browser version. This is likely done to ensure that the results are representative of a wide range of user environments.
Library: jQuery
jQuery is a popular JavaScript library that simplifies DOM manipulation and event handling. In this case, it's used to provide the addClass
method for adding CSS classes to an element.
Special JS Feature/Syntax
None mentioned in this specific benchmark, but MeasureThat.net often tests modern JavaScript features like async/await, Promises, or Web APIs (e.g., Web Storage, Web Workers).
Alternatives
Other alternatives to measure the performance of adding a CSS class include:
style.addAttribute()
: This method adds a CSS attribute to an element directly.addClass
or similar functionality.Keep in mind that these alternatives might not be as widely supported as jQuery's addClass
, and may require more knowledge of modern web development standards.