<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.0.min.js"></script>
<div id="testElement" class="test class list classes"></div>
var el = $("#testElement")[0];
var el = document.getElementById('testElement');
var el = document.querySelector("#testElement");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery | |
getElementById | |
querySelector |
Test name | Executions per second |
---|---|
jQuery | 3239820.8 Ops/sec |
getElementById | 27940814.0 Ops/sec |
querySelector | 5712176.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Overview
The provided benchmark compares the speed of getting an element by its ID using three approaches: jQuery, document.getElementById()
, and document.querySelector()
.
Library and Purpose
document.getElementById()
method is a native JavaScript function that retrieves an element by its ID.document.querySelector()
method is also a native JavaScript function that retrieves an element based on a CSS selector.Options Compared
The three options are compared in terms of their execution speed. Each test case measures how many times the code within the benchmark definition is executed per second (ExecutionsPerSecond).
Pros and Cons of Different Approaches
document.getElementById()
: Pros:document.querySelector()
: Pros:getElementById()
, but offers more flexibility with CSS selectors.getElementById()
for elements that have multiple IDs.
Cons:getElementById()
due to the overhead of parsing CSS selectors.getElementById()
or jQuery.Other Considerations
Alternatives
Other alternatives for selecting elements by ID include:
document.querySelector('#testElement')
: This method uses a single # character instead of the dot notation.element.ownerDocument.getElementById('testElement')
: This method retrieves an element from its parent document if it's not the same as the current window's document.Keep in mind that while these alternatives exist, they might not offer significant performance differences compared to the native methods used in the benchmark.