Sivaprakash B
Sivaprakash B

Reputation: 163

QuerySelector of javascript VS Find() of Jquery

On performance basics QuerySelector() of javascript or Find() of Jquery which is better to use in code on factors like speed and efficent access to Dom Elements

element = document.querySelector(selectors);

or

element= $(document).find(selectors);

Upvotes: 4

Views: 3877

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

querySelector is far more performant. It doesn't require a library nor the construction of a jQuery object.

Warning, the following will block your browser for a little bit, depending on your computer's specs:

const t0 = performance.now();
for (let i = 0; i < 1e6; i++) {
  const div = document.querySelector('div');
}
const t1 = performance.now();
for (let i = 0; i < 1e6; i++) {
  const div = $(document).find('div');
}
const t2 = performance.now();

console.log('querySelector: ' + (t1 - t0));
console.log('jQuery: ' + (t2 - t1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>some div</div>

That said, performance for selecting a single element will rarely matter - I think it would only be something to consider if it's done in a nested loop, for example, and is done thousands of times in under a second.

Upvotes: 7

Related Questions