Home > Software engineering >  JQuery Optimizing Performance With Cached Element And Selector
JQuery Optimizing Performance With Cached Element And Selector

Time:01-12

With JQuery, it is bad practice to call a selector multiple times like this:

$('#myDiv').addClass('class1');
$('#myDiv').removeClass('class2');
$('#myDiv').append(`<div>Hello World`);

So it often advised to cache the selector as such:

let element = $('#myDiv');

element.addClass('class1');
element.removeClass('class2');
element.append(`<div>Hello World`);

But lets say for example this is done:

let element = document.getElementByID('myDiv');

$(element).addClass('class1');
$(element).removeClass('class2');
$(element).append(`<div>Hello World`);

OR

let element = $('#myDiv');
$(element).addClass('class1');
$(element).removeClass('class2');
$(element).append(`<div>Hello World`);

Does either or both of those have the same negative impact when calling the selector that way?

CodePudding user response:

Using jsbench to test.

<script
  src="https://code.jquery.com/jquery-3.6.3.min.js"
  integrity="sha256-pvPw upLPUjgMXY0G 8O0xUf /Im1MZjXxxgOcBQBXU="
  crossorigin="anonymous"></script>
<div id="myDiv"></div>

29019 ops/s

$('#myDiv').addClass('class1');
$('#myDiv').removeClass('class2');
$('#myDiv').append(`<div>Hello World`);

30490 ops/s

let element = $('#myDiv');

element.addClass('class1');
element.removeClass('class2');
element.append(`<div>Hello World`);

28132 ops/s

let element = document.getElementById('myDiv');

$(element).addClass('class1');
$(element).removeClass('class2');
$(element).append(`<div>Hello World`);

31404 ops/s

let element = $('#myDiv');
$(element).addClass('class1');
$(element).removeClass('class2');
$(element).append(`<div>Hello World`);

Last one was the fastest. I am guessing because we already have a jquery reference which was then passed further. I am surprised it beat the second test case, maybe just my browser doing something. I would put the 2nd and last to be equivalent in speed.

CodePudding user response:

No, they dont have the same negative impact. You have already reference to the DOM element and there is no need to traverse DOM tree again to look for it. Both cases add some overhead and are unnecessary.

In general use chaininng where possible and keep jquery object reference if you need it frequently.

UPDATE

I wasnt right about jQuery object creation. jQuery always do some "heavy" work.

Results for one million loop on my PC:

document.getElementById("test");    // cca 37ms
$("#test");                         // cca 358ms
$(document.getElementById("test")); // cca 220ms
$(cachedDiv);                       // cca 182ms
  • Related