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) {
    function doLoop(){
          var i = LOOPS;
          do {
          } while(i);
    function run(f){
          ts = getTime();
          te = getTime();
          return te - ts;


    // result time is in seconds

    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--) {}

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

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

What type of loops do you use?

Posted by Avatar for MaBe @MaBe