for loop -vs- map

JavaScript performance comparison

Test case created by Dominic Myers

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

      
<script>
Benchmark.prototype.setup = function() {
  let objArr = [
      {
          "date": "2011-08-12T20:17:46.384Z"
      }, {
          "date": "2012-08-12T20:17:46.384Z"
      }, {
          "date": "2013-08-12T20:17:46.384Z"
      }, {
          "date": "2014-08-12T20:17:46.384Z"
      }, {
          "date": "2010-08-12T20:17:46.384Z"
      }, {
          "date": "2009-08-12T20:17:46.384Z"
      }
  ];
  
  let doubleTilde = i => ~~moment.utc(i.date).format("x");
  
  let boringParse = i => parseInt(moment.utc(i.date).format("x"), 10);
  
  let mapLessParseInt = objA => {
      let datesArr = objA.map(doubleTilde);
      return datesArr.indexOf(Math.min(...datesArr));
  };
  
  let mapLessParseIntSingleLiner = objA => objA.map(doubleTilde).indexOf(Math.min(...objA.map(doubleTilde)));
  
  let mapOne = objA => {
      let datesArr = objA.map(boringParse);
      return datesArr.indexOf(Math.min(...datesArr));
  };
  
  let forLoop = objA => {
      let min, i, objALength = objA.length;
      for (let y = 0; y < objALength; y++) {
          if (!min || moment.utc(objA[y].date).isBefore(min)) {
              min = moment.utc(objA[y].date);
              i = y;
          }
      }
      return i;
  };
  
  let forLoopInt = objA => {
      let min, i, objALength = objA.length;
      for (let y = 0; y < objALength; y++) {
          let now = boringParse(objA[y])
          if (!min || now < min) {
              min = now, i = y;
          }
      }
      return i;
  };
  
  let forLoopIntLessParseInt = objA => {
      let min, i, objALength = objA.length;
      for (let y = 0; y < objALength; y++) {
          let now = doubleTilde(objA[y])
          if (!min || now < min) {
              min = now, i = y;
          }
      }
      return i;
  };

};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
For Loop (integer comparison)
forLoopInt(objArr);
pending…
For Loop (integer comparison less parseInt)
forLoopIntLessParseInt(objArr)
pending…
Map (less parseInt)
mapLessParseInt(objArr);
pending…
Map (one line)
mapLessParseIntSingleLiner(objArr);
pending…
Map
mapOne(objArr);
pending…
For Loop
forLoop(objArr);
pending…

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

0 Comments