2

I am making fairly heavy use of jquery ui and jqgrid in the application I am working on. In most examples I see, these controls are accessed using the jquery selector to find the element by id: $("#elementid").

My question is, does jquery provide good enough performance to do this over and over or is it better practice to save references to the elements when they are first accessed: var elementName = $("#elementid");

and reuse the reference instead?

alonisser
  • 11,542
  • 21
  • 85
  • 139
zaq
  • 2,571
  • 3
  • 31
  • 39

3 Answers3

1

Using JQuery for ID is the same as getElementById() in Javascript.

As you can read here using a direct reference is faster than searching every time in the DOM tree to get your object.

IE8 getElementById: 0.4844 ms , IE8 id array lookup: 0.0062 ms

Chrome getElementById: 0.0039 ms , Chrome id array lookup: 0.0006 ms

These are the result for 10 000 get. To see the whole code for the benchmark click the link.

Community
  • 1
  • 1
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
  • half a millisecond for 10.000 lookups doesn’t count as performance gain in my world, but that decision is entirely up to the author :) – David Hellsing Nov 24 '11 at 20:14
  • Well it is mathematically. What you do with number is personal I think ;) – Patrick Desjardins Nov 24 '11 at 20:46
  • I would seem that for my purposes it's not a big deal and it saves me from littering my code with global variables to reference some of the elements. Thanks. – zaq Nov 24 '11 at 21:13
1

actually Jquery best practice is caching references. diving into to DOM each time is costly and as we learned (from one of SO founders) performance is a feature. you can look into a variery of jQuery best practice in jQuery Fundamentals

alonisser
  • 11,542
  • 21
  • 85
  • 139
0

Defining and reusing a variable is probably slightly faster and might be considered "best practice", but $('#id') maps to the native Element.getElementById which is definitely fast enough for most applications. Even if you did tests on thousands of lookups, you wouldn’t get noticeable differences for the human mind.

I’d say it’s a matter of coding style in the end.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212