Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: JavaScript
Expertise: Intermediate
Dec 5, 2005

Improve Javascript Performance by Caching Your Objects

JavaScript often repeatedly accesses a certain object, for instance:

<script language="JavaScript">
	for (i=0;i<document.images.length;i++)
           document.images[i].src="temp.gif"
</script> 
In the above example, the object document.images is accessed multiple times, forcing the browser to dynamically look it up twice during each loop (once to see if i<document.images.length, and once to access and change the image's src value at the current loop index). So if you've got ten images on the page, the script makes 20 calls to the Images object. Excessive calls like this not only slow the browser, they also take up memory, thereby slowing your system.

The way to fix this is to store a repeatedly accessed object inside a user defined variable, and use that variable instead of the actual object. Like this:


<script language="JavaScript">
	var theimages=document.images
	for (i=0;i<theimages.length;i++)
	   theimages[i].src="temp.gif"
</script> 
In the above script, document.images[] is referenced only half as many times as before. It goes to the array the second time, instead of the object.

Srinath MS
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap