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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date