<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha256-3edrmyuQ0w65f8gfBsqowzjJe2iM6n0nKciPUp8y+7E=" crossorigin="anonymous"></script>
<div id="testElement"></div>
var el = $("#testElement")[0];
var className = el.className;
var el = document.getElementById('testElement');
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery | |
Vanilla JS |
Test name | Executions per second |
---|---|
jQuery | 3609479.5 Ops/sec |
Vanilla JS | 10104743.0 Ops/sec |
Let's dive into the explanation.
Benchmark Definition
The benchmark is called "jQuery 3.3.1 slim by id vs Document.getElementById". This name indicates that we're comparing two different ways to select an HTML element using its ID, one using jQuery (a popular JavaScript library) and the other using native JavaScript (Document.getElementById()
).
Description
The description explains that this benchmark is measuring the speed of getting an element by ID using jQuery versus using native JavaScript.
Script Preparation Code
There's no special script preparation code for this benchmark. However, the HTML preparation code is provided, which includes a jQuery library reference and a simple HTML div with an ID "testElement".
Individual Test Cases
We have two test cases:
$
function to select the element by ID ($("#testElement")[0]
) and then retrieves its className
property.document.getElementById()
to select the element and then retrieves its className
property.Latest Benchmark Result
The results show two executions per second (EPS) values for each test case:
This means that, in this specific browser and environment, selecting an element by ID using native JavaScript (Document.getElementById()
) is approximately 2.8 times faster than using jQuery.
Library and Features
The benchmark uses the popular jQuery library, which provides a concise way to select HTML elements. The $
function is a key part of jQuery's API.
In this case, the test uses the $
function to select an element by ID ($("#testElement")[0]
). This approach is often referred to as a "selector" in jQuery.
Pros and Cons
Using jQuery for selecting elements has some pros:
However, it also has cons:
Native JavaScript methods like Document.getElementById()
have their own advantages and disadvantages:
Pros:
Cons:
Alternatives
If you need to select an element by ID, you can use native JavaScript methods like Document.getElementById()
or document.querySelector('#testElement')
. If you're already using jQuery in your project, you can stick with it. However, if performance is a concern, switching to native JavaScript methods might be worth considering.
Remember that this benchmark result is specific to the provided environment and browser version. Results may vary depending on your own setup.