<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.slim.min.js"></script>
<div class="test"></div>
<div class="test2"></div>
function Selector_Cache() {
var collection = {};
function get_from_cache( selector ) {
if ( undefined === collection[ selector ] ) {
collection[ selector ] = $( selector );
}
return collection[ selector ];
}
return { get: get_from_cache };
}
var selectors = new Selector_Cache();
var el = selectors.get('#test');
var el = document.getElementsByClassName('test');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery 3.2.1 Slim | |
Vanilla JS |
Test name | Executions per second |
---|---|
jQuery 3.2.1 Slim | 76483064.0 Ops/sec |
Vanilla JS | 2395570.2 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the speed of two approaches to retrieve an element by its ID:
#
selector to select an element by its ID.document.getElementById()
method to select an element by its ID.Options Compared
Two options are being compared:
Pros and Cons of Each Approach
jQuery:
Pros:
Cons:
Vanilla JS:
Pros:
document.getElementById()
method, which can be optimized by the browserCons:
Library: jQuery
jQuery is a popular JavaScript library that simplifies DOM manipulation and provides an easy-to-use API for working with HTML documents. In this benchmark, jQuery is used to provide a convenient way to select elements by their ID.
The Selector_Cache
function in the script preparation code is used to cache the results of previously executed selectors, which can improve performance by reducing the number of times the selector needs to be looked up in the DOM. This caching mechanism is a common pattern in jQuery's implementation.
Special JS Feature or Syntax
None mentioned in this benchmark.
Other Alternatives
Other alternatives for retrieving an element by its ID include:
document.querySelector()
(introduced in ECMAScript 2015)querySelector
methodNote that these alternatives may have different performance characteristics compared to jQuery or Vanilla JS.