Dave Causey
Dave Causey

Reputation: 13998

Is it a bad idea to maintain references to DOM objects and/or jQuery objects in javascript arrays?

I'm working on a web interface that requires a large number (hundreds) of DOM objects to be created and dynamically updated or removed as the underlying data changes. I'm trying to settle on the most effective strategy for keeping up with all the objects so the application scales as gracefully as possible.

My first inclination is to create arrays and hash tables referencing the DOM elements anonymously so I can find them quickly and dispatch any necessary changes. Is there a reason this approach would be problematic? Would it be better to look them up in the DOM tree instead?

What about jQuery objects? Is it better to create them frequently on the fly and allow them to be garbage collected or to keep large numbers (hundreds) of them around in some kind of structured cache?

Upvotes: 4

Views: 544

Answers (2)

mattsh
mattsh

Reputation: 6313

The time is going to be dominated by the manipulation of the contents of the elements, not by querying for them (especially if querying with selectors that use the elementID, since getElementById is very fast). I think this is more a question of code structure, rather than performance. It might be a lot of extra code to keep this hashtable in sync with the DOM, that's the main problem I see. (By the way, it sounds like what you really want is a way to declaratively express what elements in the DOM are bound to what pieces of data. There are frameworks that do this, and they take care of doing the update and keeping everything in sync.)

Upvotes: 1

Ivan Castellanos
Ivan Castellanos

Reputation: 8243

Is better to keep one jQuery Object instead of creating them multiple times. But keep in mind that the bottleneck in Javascript is DOM manipulation, not saving references of its elements.

I just made some tests with 10000 divs and is significantly faster to have everything in a array/jquery object than look it up everytime in the DOM.

Use IDS and indexes for maximum efficiency (Many people use old browsers that don't have a native class selector) ie:

var allElements = $("#container").children()
allElements.eq(10).hide()

Upvotes: 2

Related Questions