I’m building one of my first web apps using HTML5, specifically targeting iPhones.
Since I’m pretty new to this, I’m trying to develop some good coding habits, follow best practices, optimize performance, and minimize the load on the resource-constrained iPhone.
One of the things I need to do frequently… I have numerous divs (each of which has a unique id) that I’m frequently updating (e.g., with innerHTML), or modifying (e.g., style attributes with webkit transitions and transforms).
In general – am I better off using getElementByID each time I need a handle to a div, or should I store references to each div I access in “global” variables at the start?
(I use “global” in quotes because I’ve really just got one truly global variable – it’s an object that stores all my “global” variables as properties).
I assume using getElementByID each time must have some overhead, since the function needs to traverse the DOM to find the div. But, I’m not sure how taxing or efficient this function is.
Using global variables to store handles to each element must consume some memory, but I don’t know if these references require just a trivial amount of RAM, or more than that.
So – which is better? Or, do both options consume such a trivial amount of resources that I should just worry about which produces more readable, maintainable code?
Many thanks in advance!
When you’re calling
getElementById, you’re asking it to perform a task. If you don’t expect a different result when calling the same method with the same argument, then it would seem to make sense to cache the result.In modern browsers especially, it’s very fast, but not as fast as looking up a property on your global object.
Trivial. It’s just a pointer to an object that already exists. If you remove the element from the DOM with no intention to use it again, then of course you’ll want to release your hold on it.
Depends entirely on the situation. If you’re only fetching it a couple times, then you may not find it worthwhile to add to your global object. The more you need to fetch the same element, the more sense it makes to cache it.
Here’s a jsPerf test to compare. Of course size of your DOM as well as length of variable scope traversal and the number/depth of properties in your global object will play some role.