18

Let's say I have this block of code:

$('#myBox').css('background', 'grey');
$('#myBox').click( function(e){ console.log( 'Box clicked' ); });
$('#myBox').html(' Just a test text ');

What I know so far is that I'm searching an element with the myBox ID at every line. The question: would I benefit from a variable creation when I have multiple references to an HTML element?

Or will the variable still search for the associated element every time I access it? Example:

var $myBox = $('#myBox');

$myBox.css('background', 'grey');
$myBox.click( function(e){ console.log( 'Box clicked' ); });
$myBox.html(' Just a test text ');
Machavity
  • 30,841
  • 27
  • 92
  • 100
Luca Rossi
  • 409
  • 3
  • 12
  • 11
    When you save in variable it won't again look in DOM. so this is better than first one. – shyammakwana.me Oct 26 '17 at 12:52
  • 1
    As I know we should always use variables. \ – Harden Rahul Oct 26 '17 at 13:17
  • 5
    Best practice? Get a functional website then identify where the performance problems lie. If there's a problem, you'll see it. – corsiKa Oct 26 '17 at 15:50
  • 1
    I assume you've probably structured it this way for example purposes, but just in case someone doesn't know, for this particular case you should just use method chaining `$("#myBox").css(...).click(...).html(...);` – thegreatemu Oct 26 '17 at 20:06
  • The only way to answer this question is by benchmarking it. What happened when you put together a test and measured the performance? – Kevin Workman Oct 26 '17 at 20:30
  • I didn't test yet, it just seemed 'wrong' for me before I edited thanks to all these guys. My project seems smoother but I have still a lot of work to do! I will try to update this situation in the immediate future :) – Luca Rossi Oct 26 '17 at 20:37

3 Answers3

17
var $myBox = $('#myBox');

Is more efficient, but it can be worse when '#myBox' changes dynamically. If you save var $myBox but than '#myBox' changes you will have to manually reassign var $myBox which is really troublesome for large applications. In general i would say you are better of keeping such optimizations in a scope of one function instead of whole application.

A very simple example is here in plunkr. A more realistic one would be when content changes according to some API call.

guramidev
  • 2,228
  • 1
  • 15
  • 19
  • 1
    I'm developing a simple webgame, so most of the work I will do on elements will be graphical or event binding. I guess having a variable will help me a lot! Thank you guramidev! – Luca Rossi Oct 26 '17 at 12:58
  • 1
    I would guess the game is more of a turn-based one than action one, in which case i would do the same. But if you are developing some action game where you use jQuery selector per every frame than i would prefer to keep global state of selected elements...but than again developing action game with HTML is questionable itself, just use some HTML5 engine like Phaser3 – guramidev Oct 26 '17 at 13:03
  • It's a quiz game. I never really delete elements since I use them very often, so having them stored in variables I think will help me much. Thank you for the Phaser3 tip. – Luca Rossi Oct 26 '17 at 13:10
  • 1
    Yea well from pure performance perspective it is better to store, just wanted to point out the caveat – guramidev Oct 26 '17 at 13:11
  • 1
    The variable is a reference to the element, so it doesn't matter if the contents change. The only problem comes if the original element is removed and another element is added with the same id, then the variable points to the original element, not the new one. – JJJ Oct 26 '17 at 14:52
  • This answer seems just wrong to me or I misunderstand it. Would you mind adding an example where assigning the variable once would cause troubles? – xehpuk Oct 26 '17 at 15:19
  • @xehpuk added plunkr, sorry if it feels weird a bit xD – guramidev Oct 26 '17 at 17:06
  • 1
    The plunkr removes the entire element, not only its contents. The answer is still misleading. – JJJ Oct 26 '17 at 17:51
  • @JJJ thank you for pointing that out, it was indeed misleading. Changed the answer so that "content" is not shown as the main idea. – guramidev Oct 26 '17 at 18:35
6

You can measure the performance comparing the miliseconds that takes to execute each code.., I would say executing with a variable has a better performance because it assign the jquery element just the first time

var time = new Date().getTime();
$('#myBox').css('background', 'grey');
$('#myBox').click( function(e){ console.log( 'Box clicked' ); });
$('#myBox').html(' Just a test text ');
console.log('Miliseconds without variable',new Date().getTime() - time);

var time2 = new Date().getTime();
var $myBox = $('#myBox2');

$myBox.css('background', 'grey');
$myBox.click( function(e){ console.log( 'Box clicked' ); });
$myBox.html(' Just a second text ');
console.log('Miliseconds with variable',new Date().getTime() - time2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myBox"></div>
<div id="myBox2"></div>
Renzo Calla
  • 7,486
  • 2
  • 22
  • 37
  • 1
    I'd us performance.now() for measuring code runtime, Date isn't really meant to handle that: https://jsfiddle.net/0hub8zd6/ – DasBeasto Oct 26 '17 at 19:28
4

Reusing the selector reference, your second case, is definitely faster. Here's a test: http://jsperf.com/caching-jquery-selectors The latter case, redefining your selectors, is reported as ~35% slower.

ferhado
  • 2,363
  • 2
  • 12
  • 35