map array or loop

Benchmark created on


Setup

var pts = [];
    for (var i = 0; i < 1000; i++) {
      pts[i] = { x: i, y: i };
    }
    
    var hardTransform = function (pt) {
      return { x: pt.x * 0.5, y: pt.y + 1 };
    };
    
    var obj = {
      a: 0.5,
      b: 1,
      _transform: function (pt) {
        return { x: pt.x * this.a, y: pt.y + this.b };
      },
      method1: function (arr) {
        return arr.map(this._transform, this);
      },
      method2: function (arr) {
        return arr.map(hardTransform);
      },
      method3: function (arr) {
        var res = [];
        for (var i=0,len=arr.length;i<len;i++) {
          res.push(this._transform(arr[i]));
        }
        return res;
      },
      method4: function (arr) {
        var res = [];
        for (var i=0,len=arr.length;i<len;i++) {
          var pt = arr[i];
          res.push({ x: pt.x * this.a, y: pt.y + this.b });
        }
        return res;
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
map-this
obj.method1(pts);
ready
map-static-callback
obj.method2(pts);
ready
loop-and-transform
obj.method3(pts);
ready
loop-inline-transform
obj.method4(pts);
ready

Revisions

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