Test on "for" loop refactored

Benchmark created by NinjaTux on


Setup

var itemsArray = ["apple", "apricot", "ananas", "banana", "cherry", "lampone", "mango"];
    // Fake function
    function doSomethingCommon() {
      var a = 0, b = 3;
      while(b--) {
        a = a + b;
      }
    }
    // Fake function
    function doSomethingCommonAgain() {
      var a = 0, b = 3;
      while(b--) {
        a = a + b;
      }
    }
    // Fake function
    function displayAfter(item) {
      var a = 0, b = 3;
      while(b--) {
        a = a + b;
      }
    }
    // Fake function
    function displayBefore(item) {
      var a = 0, b = 3;
      while(b--) {
        a = a + b;
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
First step
function addItem(itemsArray, direction) {
  "use strict";
  var i, l;
  if(direction && direction === "up") {
    i = itemsArray.length -1;
    for(;i > 0; i-=1){
      doSomethingCommon();
      displayBefore(itemsArray[i]);
      doSomethingCommonAgain();
    }
  } else {
    i = 0, l = itemsArray.length;
    for(; i < l; i+=1) {
      doSomethingCommon();
      displayAfter(itemsArray[i]);
      doSomethingCommonAgain();
    }
  }
}

addItem(itemsArray);
addItem(itemsArray, "up");
ready
Second step
function addItem(itemsArray, direction){
  "use strict";
  var i, l, check, next;
  if(direction && direction === "up") {
    i = itemsArray.length - 1;
    check = function () { return i >= 0; };
    next = function () { return i--; };
  } else {
    l = itemsArray.length,
    i = 0;
    check = function () { return i < l; };
    next = function () { return i++; };
  }
  for(; check(); next()) {
    doSomethingCommon();
    if(direction && direction === "up") {
      displayBefore(itemsArray[i])
    } else {
      displayAfter(itemsArray[i]);
    }
    doSomethingCommonAgain();
  }
}

addItem(itemsArray);
addItem(itemsArray, "up");
ready
Third snippet
function addItem(itemsArray, direction){
  "use strict";
  var i, l, check, next, behavior;
  if(direction && direction === "up") {
    i = itemsArray.length - 1;
    check = function () { return i >= 0; };
    next = function () { return i--; };
    behavior = displayBefore;
  } else {
    l = itemsArray.length,
    i = 0;
    check = function () { return i < l; };
    next = function () { return i++; };
    behavior = displayAfter;
  }
  for(; check(); next()) {
    doSomethingCommon();
    behavior(itemsArray[i]);
    doSomethingCommonAgain();
  }
}

addItem(itemsArray);
addItem(itemsArray, "up");
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by NinjaTux on