If you’re like me and use a lot of framework singletons, such as the popular YAHOO.util.Dom, there’s something you can do so speed things up.
Every time you use a global variable, the browser has to work its way up the scope chain until it reaches the global scope. By giving all those pesky global vars a local reference, you can significantly lower the time it takes to find that variable.
Remember, JavaScript code is executed on the end-user’s computer, so writing efficient code should always be the #1 priority. Here’s an example with using YUI core components which are accessed frequently:
(function() {
var lang = YAHOO.lang,
dom = YAHOO.util.Dom,
event = YAHOO.util.Event;
var newObject = function() {
// 'lang' is much faster to lookup than 'YAHOO.lang' and so on...
alert(lang.JSON.stringify({"key" : "value"}));
};
})();
By writing your code within a self-executing function, variables lang, dom, and event are only local to that function and everything inside of it. So, lookups to such frequent tools like YAHOO.util.Dom are much faster.
Similarly, lowering the times you access the DOM improves the performance as well, most of the times drastically.
So if you have something along the lines of this (but hopefully more profound):
for (var i=0; i<100; i++) {
document.getElementById('el').innerHTML = i;
}
Do this:
var el = document.getElementById('el');
for (var i=0; i<100; i++) {
el.innerHTML = i;
}
In other words, only do one DOM lookup per element and save the reference to a variable.
That’s it. Happy coding.
Unfortunately, no one has commented yet
RSS Feed Really Simple Syndication for you!
This blog focuses primarily on technology, web development, and entrepreneurship. 50% of the time I'm right every time, so stick around and enjoy the show.