Improve Javascript Performance by Caching Your Objects

Improve Javascript Performance by Caching Your Objects

JavaScript often repeatedly accesses a certain object, for instance:


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, 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:


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.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist