简体   繁体   中英

Storing an element vs. its id, what's the most efficient

On a page, I have several elements on which I need to perform repetitive operations. To avoid traversing the DOM every time, I want to store a reference to all these elements in an array (or an object).

Each of these elements has an id.

What is the most efficient: store the ids in my array, or store the elements themselves?

If I store the ids, then every time I want to access the elements I need to call getElementById. If I store the elements themselves, then my feeling is that it requires more "effort" from the browser (although I have no idea how it works in practice, and would be interested to know more).

Much, much more efficient to store the element reference rather than just the id , because as you said, you avoid the lookup when you go to do operations on it.

The downside to storing the element reference is that you have a reference to the element (that's the whole point), and so if you remove the element from the DOM, you have to be sure to also release your reference to it or it will remain in memory. If these elements always exist on your page and never get removed, that's fine, though I would recommend an unload handler that releases all of your references to the elements just to be sure older versions of IE don't do silly things like keep them around even after the user has left the page.

You're not storing the element in an array but a reference to an element in the DOM. I'd go with storing a reference to the element over storing its ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM