JavaScript Loop Optimization

01.06.2015

Cache lengthy repetitive access to the same data.

Before

for(var i = 0; i < treasureChest.necklaces.length; i++) { 	
  console.log(treasureChest.necklaces[i]);!
}

After

var list = treasureChest.necklaces;
for(var i = 0, x = treasureChest.necklaces.length; i < x; i++) {
  console.log(list[i]);
}

This saves on repeated memory access steps. This is significant when dealing with large amounts of data.

Sources

https://www.codeschool.com/courses/javascript-best-practices