<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<a href="#" class="dz-class" data-plugin="dz-plugin" data-plugin-dz>My link</a>
<form>
<input type="text" class="dz-class" data-plugin="dz-plugin" value="My input text" data-plugin-dz>
$elements = $('.dz-class');
$elements = $('[data-plugin="dz-plugin"]');
$elements = $('[data-plugin-dz]');
$elements = $('.dz-class[data-plugin="dz-plugin"]');
$elements = $('.dz-class[data-plugin-dz]');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Class | |
Data by value | |
Data directly | |
Class + Data by value | |
Class + Data directly |
Test name | Executions per second |
---|---|
Class | 180880.4 Ops/sec |
Data by value | 122770.4 Ops/sec |
Data directly | 120482.2 Ops/sec |
Class + Data by value | 128670.2 Ops/sec |
Class + Data directly | 133866.1 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares different ways to select elements using jQuery selectors in a specific HTML structure. The goal is to determine which approach is the fastest.
Selectors Compared
The benchmark defines four different selectors:
.dz-class
: Selects elements with class dz-class
.[data-plugin="dz-plugin"]
: Selects elements with attribute data-plugin
having value dz-plugin
.[data-plugin-dz]
: Selects elements with attribute data-plugin-dz
..dz-class[data-plugin="dz-plugin"]
: Combines classes and data attributes.Library Used
The benchmark uses jQuery, a popular JavaScript library for DOM manipulation and event handling. In this case, it's used to execute the selectors on the HTML structure defined in the "Html Preparation Code".
Special JS Feature/Syntax
None of the selected approaches utilize any special JavaScript features or syntax beyond standard CSS selectors.
Pros and Cons of Each Approach
.dz-class
: This approach selects elements by class name, which can be slower than other methods because it requires parsing the entire class list.[data-plugin="dz-plugin"]
and [data-plugin-dz]
: These approaches select elements by attribute, which can be faster because it only requires checking a single attribute..dz-class[data-plugin="dz-plugin"]
: This approach combines classes and data attributes, which can be faster than individual class or attribute selection because it reduces the number of elements to check.Other Alternatives
If you had more control over the HTML structure, you could also consider using other selectors like:
:has()
for combining multiple selectors or attributes.[selector1][selector2]
for combined selections.^=selector
and $=selector
for attribute-based selections.However, these alternatives might require specific browser support or HTML structure modifications.
In conclusion, the benchmark highlights the importance of considering attribute-based selection when working with modern web applications, especially those using jQuery or other libraries that rely on attribute selectors.