zaq
zaq

Reputation: 2661

jQuery - performance accessing elements

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?

Upvotes: 2

Views: 163

Answers (3)

alonisser
alonisser

Reputation: 12068

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

Upvotes: 1

Patrick Desjardins
Patrick Desjardins

Reputation: 140753

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.

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108480

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.

Upvotes: 0

Related Questions