<div id="foo" class="bar" data-hook="test">Hello World</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
document.getElementById("foo");
document.getElementsByClassName("bar");
document.querySelectorAll('.bar');
document.querySelector('.bar');
document.querySelectorAll('[data-hook="test"]');
$("#foo");
$(".bar");
$('[data-hook="test"]');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Vanilla JS ID Selector | |
Vanilla JS Class Selector | |
Vanilla JS Query Selector All | |
Vanilla JS Query Selector | |
Vanilla JS Data Hook | |
jQuery ID Selector | |
jQuery Class Selector | |
jQuery Data Hook Selector |
Test name | Executions per second |
---|---|
Vanilla JS ID Selector | 10798367.0 Ops/sec |
Vanilla JS Class Selector | 10817609.0 Ops/sec |
Vanilla JS Query Selector All | 3524325.8 Ops/sec |
Vanilla JS Query Selector | 6817187.0 Ops/sec |
Vanilla JS Data Hook | 2855925.0 Ops/sec |
jQuery ID Selector | 12213208.0 Ops/sec |
jQuery Class Selector | 3331221.2 Ops/sec |
jQuery Data Hook Selector | 1883352.1 Ops/sec |
Let's dive into the benchmark test and its various components.
Benchmark Definition
The benchmark is designed to compare the performance of different JavaScript methods for selecting elements in HTML documents. The tests are categorized as follows:
Options Compared
Each test case compares the performance of a specific JavaScript method or library:
document.getElementById()
(ID selector)document.getElementsByClassName()
(class selector)document.querySelectorAll()
(query selector all) and document.querySelector()
(query selector)document.querySelector('[data-hook="test"]')
(data hook selector)$()
(jQuery ID selector), .()
(jQuery class selector), and [data-hook="test"]
(jQuery data hook selector)Pros and Cons of Each Approach
Here's a brief overview of the pros and cons of each approach:
Library Usage
The test cases using jQuery ($()
and [data-hook="test"]
) are part of the jQuery library. The purpose of these libraries is to provide a convenient way for developers to manipulate HTML documents, making it easier to select and interact with elements.
$(selector)
is the primary function used by jQuery to select elements from the DOM.[data-hook="test"]
is an attribute selector that uses data hooks to select elements based on their presence in the DOM. This feature allows for more flexibility in selecting elements, especially when dealing with dynamically generated content.Special JS Features/Syntax
The test cases do not explicitly mention any special JavaScript features or syntax beyond what's necessary for the benchmark. However, keep in mind that Vanilla JS methods can be optimized using advanced techniques like memoization or caching to improve performance.
Other Alternatives
For similar benchmarks, you may want to explore other alternatives:
Keep in mind that each benchmark should be tailored to its specific use case and requirements.