Search code examples
javascriptjqueryloopsecmascript-5

Which is the fastest way to loop? [for curiosity]


I'm trying to increase a variable from 0 to 1000000 in a fastest way. In this case i need to increase the variable value and measure the time to run all of this loops. Should i use a while loop, or a setInterval() with 0 of time interval is fastest?

var i = 0;
while(i <= 1000000){
  i++;
}

//VS

var i = 0;
setInterval(function(){
  if(i <= 1000000){
    i++
  }
},0)

//OTHER OPTIONS
//...

And how to measure that?

UPDATE

I think I expressed myself wrong, I want to actually reach 1 million by adding one by one to the variable. And thats my issue in measuring that, wich is the best way?


Solution

  • Performing tests i discover that the for loop is the better option for this situation:

    for(var i = 0; i < 1000000; ++i){
    
          // Each iteration of the loop will make i
          // have a different value inside the loop
    
     }
    

    And for measure the time i'm using console.time() and console.timeEnd()