# What type of loops do you use?

Posted on
• There has been a lot talking about loop performance.

So lets's try to find out if there is a difference between loops and loops.

Tested on an original Espruino board so others may differ for the time but not for the result.

``````VERSION: "2v05",
GIT_COMMIT: "990dac35",
BOARD: "PICO_R1_3",
``````

Test code snipped with for, while and do.

``````var LOOPS = 1E4;

function forLoop(){
for (i = 0; i < LOOPS; i++) {
x = 0;
}
}

function whileLoop(){
var i = LOOPS;
while (i) {
i--;
}
}

function doLoop(){
var i = LOOPS;
do {
i--;
} while(i);
}

function run(f){
ts = getTime();
f();
te = getTime();
return te - ts;
}
``````

testing:

``````// result time is in seconds
>run(forLoop)
=2.67205524444

>run(whileLoop);
=1.25568199157

>run(doLoop);
=1.31462860107
``````

As a result: Try to use do or while loops instead of for loops , they run nearly twice as long.

• It's not an entirely fair comparison if you've got `x=0` in the for loop but not in any other loops, but I believe `for` will be slower anyway, just because Espruino is having to jump between 3 different places (the loop iterator, condition and body)...

The fastest would be:

``````      var i = LOOPS;
while (i--) {
}
``````
• Well not sure about this, isn't `x=0` faster than `i++, but let's compare the empty loops.

``````function forLoopV2(){
for (i = 0; i < LOOPS; i++) {}
}

function whileLoopV2(){
var i = LOOPS;
while (i--) {}
}
``````
``````>run(forLoopV2)
=1.96909236907
>run(whileLoopV2)
=0.91626548767
``````

Any way it is clear that while loops are faster than for loops.

• Post a reply