<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<ul>
<li class="c">Foo</li>
<li class="c">Bar</li>
<li class="c">Baz</li>
</ul>
$('li.c');
$('.c');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
tag.class | |
.class |
Test name | Executions per second |
---|---|
tag.class | 69109.6 Ops/sec |
.class | 167385.1 Ops/sec |
I'd be happy to explain what's being tested in the provided benchmark.
What is tested:
The benchmark measures the performance difference between two ways of selecting elements with a class using jQuery:
tag.class
: This method uses the class
attribute of an HTML element to select all elements that have both classes "c". In other words, it looks for elements like <li class="c">Foo</li>
..class
: This method uses a CSS selector syntax with a dot (.
) instead of a hyphen (-
) to select elements with the class "c".Options compared:
The benchmark compares the execution speed of these two approaches:
tag.class
.class
Pros and cons of each approach:
tag.class
:.class
:tag.class
.Library:
The benchmark uses jQuery, a popular JavaScript library for DOM manipulation. In this case, it's used to select elements with a specific class.
Special JS feature or syntax:
This benchmark doesn't use any special JavaScript features or syntax. However, it does rely on the fact that modern browsers support CSS selectors in their DOM manipulation APIs.
Other alternatives:
If you want to compare the performance of these two approaches without using jQuery, you can also consider using a plain JavaScript implementation with document.querySelectorAll
and document.getElementsByClassName
. The benchmark might look something like this:
{
"Name": "jQuery `tag.class` vs `.class`",
"Description": null,
"Script Preparation Code": null,
"Html Preparation Code": "<html><body><ul><li class=\"c\">Foo</li><li class=\"c\">Bar</li><li class=\"c\">Baz</li></ul></body></html>"
}
Individual test cases:
[
{
"Benchmark Definition": "document.querySelector('li.c');",
"Test Name": "tag.class"
},
{
"Benchmark Definition": "document.getElementsByClassName('c')[0];",
"Test Name": ".class"
}
]
Keep in mind that this plain JavaScript implementation would require additional setup, such as creating a function to parse CSS selectors and generate the corresponding jQuery-like selector string.