[Javascript]1. Improve you speed! Loop optimaztion
/** Improve you loop code */ var treasureChest = { goldCoins: 10000, magicalItem : "Crown of Speed", necklaces: ["ruby", "pearl", "sapphire", "diamond"], openLid: function(){ alert("openLid"); } }; console.log("You found the following necklaces: "); // //**BAD** // for(var i = 0; i < treasureChest.necklaces.length; i++){ console.log(treasureChest.necklaces[i]); } //The code need to do many things: //1. the value of i //2. the treasureChest object //3. necklaces property //4. the array pointed to by the property //5. the length property of the array //Count steps: //5 steps * (4 loops + 1 check to stop) = 25 steps /* What step we can eliminate? Use "cached values" to curtail lengthy, repetitive to the same data */ var x = treasureChest.necklaces.length; for(var i = 0; i < x; i++){ console.log(treasureChest.necklaces[i]); } //Memory access during loop control now only needs to: //1. retrieve the value of i //2. retrieve the value of x //----------- for creating x-------------- //1. ONE TIME COST, creating the variable x in memory //2-5: the 4 steps finding the value of length //Count steps: //2 steps * (4 loops + 1 check to stop) + 5 create extra variable = 15 steps //So we got 25 - 15 = 10 steps less, imaging we have 10000 datas! //The difference would be: //5 steps * (10000 loops + 1 check to stop) = 50005 steps //2 steps * (10000 loops + 1 check to stop) + 5 extra steps for x = 20007 steps //The difference would be: //50005 - 20007 = ~30000 !!!! /** Place your extra control variables inside the loop */ for(var i = 0, x = treasureChest.necklaces.length; i < x; i++){ console.log(treasureChest.necklaces[i]); } /** Avoid repetitive access at depth */ var list = treasureChest.necklaces; for(var i = 0, x = treasureChest.necklaces.length; i < x; i++){ console.log(list[i]); } /** Choose the best loop for arrays, for-loop usually better than for-in loop */ Array.prototype.countType = function(type){ ... } Array.prototype.removeAll = function(item){ ... } var list = treasureChest.necklaces; for(p in list){ console.log(list[i]); } //will console out: //"ruby", "pearl", "sapphire", "diamond", "countType", "removeAll" //"countType", "removeAll", those are not we want! //The reason for this is because for-in loop is a property approach to access //indices will also add in all methods that have been added to the Array prototype. //prototype makes methods we add becomes Enumerable just like indices.