Minimize Lookups to Speed up JavaScript
A new post on the IEBlog has some decent tips on optimizing the performance of your scripts. Although written specifically addressing performance issues as they relate to Internet Explorer, I suspect most of the suggestions would appy to other browsers as well.
The summary of the article, the first of a three part series, is to:
- Declare
var
for variables that are meant to have local scope - Cache DOM elements and function lookups that need to be re-used
- Avoid using
with
Declare var
for variables is something most of us are (or should be) doing and avoiding the use of with
seems simple enough since I never use it anyways. What's interesting are some of the tips that they provide for caching DOM elements and function lookups. In particular, I want to highlight one of the code examples they give.
function IterateWorkOverCollection()
{
var funcAppendChild = document.getElementById(‘target’).appendChild;
var length = myCollection.getItemCount();
for(var index = 0; index<length; index++)
{
funcAppendChild(myCollection[index]);
}
}
You'll notice that they cache the pointer to the appendChild function. At least in my version of Firefox (version 1.5.0.6), this does not work and will throw an error the moment you try to do so.
Conversation
Are those unusual looking characters supposed to be there (‘ ... ’), or is my browser/your CMS rendering them this way?
If they are meant to be this way, what are they? And how are they used?
If not, is anyone else seeing these, or am I on crack?
BTW, just checked this entry in IE6.0, and encountered an error that wouldn't allow this page to be rendered.
"Internet Explorer cannot open the internet site http://www.snook.ca/archives/javascript/minimize_lookup/.
Operation Aborted"
Just a heads up.
Sometimes those characters are a result of the fact that my host keeps feeding files out as iso-8859 where they should be UTF-8 (which will be fixed when I roll out a new backend).
I didn't escape one of the characters which hopefully explains some rendering issues.
Caching functions of the DOM is a very bad idea as it depends on the browser implementation, so portability is low.
What must be cached is DOM data objects:
I wonder also about the performance of nextSibling instead of accessing to an element by index.
Olivier Mengu
Very true, "caching" the DOM objects rather then the Objects methods is also a modular approach. If you wanted to use multiple methods/properties of the DOM object, they are a single method/property away. Caching a method limits you to just the use of that single reference.