<script src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="outer">
<div class="inner"></div>
</div>
$('.outer .inner').on('click', function (e) {});
const $outer = $('.outer');
$outer.find('.inner').on('click', function (e) {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery raw | |
jQuery find |
Test name | Executions per second |
---|---|
jQuery raw | 849999.4 Ops/sec |
jQuery find | 616466.9 Ops/sec |
The provided benchmark evaluates the performance of two different methods of selecting DOM elements and attaching event handlers using jQuery, a popular JavaScript library for simplifying HTML document traversal and manipulation.
<div>
elements.Test Case 1: jQuery raw
$('.outer .inner').on('click', function (e) {});
Test Case 2: jQuery find
const $outer = $('.outer'); $outer.find('.inner').on('click', function (e) {});
$outer
variable holds a jQuery object representing the outer <div>
. The .find()
method is called on this jQuery object to search for the inner element, after which the click event handler is attached.According to the benchmark results:
Pros:
Cons:
Pros:
Cons:
.find()
method is beneficial when dealing with a large DOM where limiting the search scope can significantly enhance performance.While the benchmark showcases jQuery for DOM manipulation, there are numerous alternatives:
Vanilla JavaScript:
document.querySelector()
and element.addEventListener()
can be faster in terms of performance when jQuery isn't needed. It also avoids loading an additional library.Other Libraries or Frameworks:
Lightweight Libraries:
In summary, this benchmark provides insights into the use of different selector strategies within jQuery, highlighting trade-offs between straightforward syntax versus contextual efficiency. Understanding these aspects aids developers in making informed choices based on specific performance needs and application complexity.