Thursday, January 19, 2017

JavaScript: Loop Optimazation

Here are the common For loop scenario.
let data = {name:["Simon", "Alvin", "Sharmal"]};

for(let i=0; i<data.name.length; i++){
  console.log(data,name[i]);
};
This is not  the best way because, at the start of each potential loop cycle, the program will need to find and retrieve:
  1. the value of i
  2. the data object
  3. the name property
  4. the array pointed by the property
  5. the length property of the array
We can use "caches values" to curtail lengthy, repetitive access to the same data.
let data = {name:["Simon", "Alvin", "Sharmal"]};

for(let i=0, x= data.name.length; i<x; i++){
  console.log(data,name[i]);
};
Memory access during loop control now only needs to:
  1. retrieve the value of i
  2. retrieve the value of x

No comments:

Post a Comment