One of the best kept secrets to boosting script performance is to
cache your objects. Often times, your script will repeatedly access a
certain object, as in the following demonstration:
In the above, the object "document.images" is what's accessed multiple
times. The code to realizing it is inefficient, since the browser must
dynamically look up "document.images" twice during each loop (once to
i<document.images, and the other, to access and change the
src). If you have 10 images on the page, for example, that's
20 calls to the Images object right there. Excessive calls to
The term "cache your object" means storing a repeatedly access object
inside a user defined variable, and using that variable instead in
subsequent references to the object. The performance improvement can
be significant. Here's a modified version of the initial script using
Not only is the number of times document.images is referenced cut in
half with the above, but for each time it is referenced, the browser
doesn't have to go through document.images first, but goes straight to
its containing array.
Remember to use object caching when calling highly nested DHTML
objects, like document.all.myobject, or document.layers.firstlayer
While recognizing exactly which isn't easy (and isn't the goal here),
just becoming aware of this fact is important.
Take, for example, these two properties:
-object.innerText //IE only
Did you know that the second property demands multiple times the
system resources to call than the first? If all you're changing is the
textual content of a
<span> and in IE only,
definitely be the more efficient choice. Another example are the CSS
display" and "
visibility"; the former is significantly
more expensive than the later.