<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
<div class="foo"></div>
var querySelectorSupported = document.querySelectorAll;
(function ()
{
var jQueryInitFunc = $.fn.init;
$.fn.init = function (selector, context, root)
{
if (querySelectorSupported
&& !context
&& typeof selector === "string"
&& selector[0] !== "<")
{
try
{
selector = document.querySelectorAll(selector);
}
catch (e)
{
}
}
return new jQueryInitFunc(selector, context, root);
};
})();
(function ()
{
var jQueryFindFunc = $.fn.find;
$.fn.find = function (selector)
{
if (querySelectorSupported
&& typeof selector === "string")
{
try
{
return $(Array.from(this.get(0).querySelectorAll(selector)));
}
catch (e)
{
}
}
return jQueryFindFunc.apply(this, arguments);
};
})();
$(".foo");
$(".foo");
document.querySelectorAll(".foo");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Extension override | |
Jquery | |
Native |
Test name | Executions per second |
---|---|
Extension override | 724.0 Ops/sec |
Jquery | 328.6 Ops/sec |
Native | 852981.2 Ops/sec |
Let's break down the benchmark definition and test cases to understand what is being tested.
Benchmark Definition
The benchmark measures the performance of three approaches:
document.querySelectorAll
method directly.$.fn.init
and $.fn.find
methods to mimic its behavior using native DOM methods.Script Preparation Code
The script preparation code includes a reference to the jQuery library (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js
) and some HTML code with multiple elements having class foo
.
Individual Test Cases
Each test case has a unique benchmark definition that defines a specific scenario:
$.fn.init
and $.fn.find
methods to mimic its behavior using native DOM methods.querySelectorSupported
method is available, and if not, tries to execute a native document.querySelectorAll
call.$
function on an element with class foo
.document.querySelectorAll
method directly.Pros and Cons
Here are some pros and cons of each approach:
Libraries
The test cases use the following libraries:
Special JS Features or Syntax
There are no special features or syntax mentioned in the benchmark definition or individual test cases.
Alternatives
If you need to compare performance with alternative implementations, here are some options:
Note that each of these alternatives has its own strengths and weaknesses, and the choice of implementation will depend on the specific requirements of your project.