2

Can anyone explain if using the object variable selector offers better performance compared to the traditional $("#selector") in jQuery?

<form id="my_form" action="www.test.com" method="POST">
  <input type="text" id="name">
  <button type="submit" class="" style="">SEND</button>
</form>
$(document).ready(function() {    
  var my_form = $("#my_form"); // object variable selector    
  my_form.trigger("reset"); 

  // or

  $("#my_form").trigger("reset");    
});

Let's just say that I will be using the $("#my_form") more than ten times to manipulate the child elements in the DOM.

Is it better if just store the selector as an object variable for better performance or it doesn't make a difference?

redshot
  • 2,930
  • 3
  • 31
  • 68
  • 1
    If you're going to be re-selecting the same element multiple times, then storing the jQuery object in a variable is always much faster as it negates the need to read data from the DOM, which is comparatively much slower. – Rory McCrossan Jun 07 '19 at 12:28
  • I think the real question is **Will you need `my_form` after the trigger or not** that the only reason to create a variable before using it. – Core972 Jun 07 '19 at 12:29
  • 1
    Yes. `var my_form = $("#my_form");` is always preferred as long as the form does not change. That way you don't have to requery the DOM or the jquery cache. Thank you, it's a big pet peeve of mine seeing people using jquery to requery the DOM for every single change. – Shilly Jun 07 '19 at 12:30
  • @RoryMcCrossan that is great to hear. Can you please write your comment as an answer. – redshot Jun 07 '19 at 12:30
  • @Core972 yes of course. – redshot Jun 07 '19 at 12:33

2 Answers2

2

I don't know about performances but as @Rory McCrossan said its supposed to be faster to store it.

And for maintenance, if you needs to modify it, as you use it several times, it's better to store. Then you'll need to modify the value only one time

axel axel
  • 253
  • 1
  • 11
2

If you're going to be re-selecting the same element multiple times, then storing the jQuery object in a variable is always much faster as it negates the need to read data from the DOM, which is comparatively much slower.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you.. Btw, I am not just re-selecting the element but also selecting the child elements for other purposes – redshot Jun 07 '19 at 12:35