Cache that Value – Loop Optimization in JavaScript

Say we have a javascript object called bookstore and bookstore object has an array of fictions.

var bookstore = {

fictions : {






Now we want to print out the names of fictions this bookstore has.

So we can write a for loop to do our work.

for(var i = 0; i < bookstore.fictions.length; i++ ){



Every time it iterates through the loop it access the memory where bookstore is, then go find the fictions array and find the length of it. So there are 3 steps involved just to get the length of the fictions array. and since there are 3 elements in the array it check the loop condition for 3 times + loop break, all together 4 times. If we do the math finding this length involves 4 * 3 = 12 steps of memory access. Can you imaging how many steps involved if the number of items in the loop is more than this. Disaster! isn’t it?

According to the best practices in Javascript lesson of CodeSchool, we can do much better than that.

Lets see how we can optimize the loop,

for(var i = 0, noOfFictionsInStore=bookstore.fictions.length;
i < noOfFictionsInStore; i++ ){



So what we are doing here we cache the length value to a local variable when the loop initialize its variables and use that cached value directly. This will reduce the number of memory accessing steps and that number of steps reduction is huge, when our array has so many elements.



Author: Harshani Nawarathna

Sri Lankan woman in Computing

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s