for-in-testing

Benchmark created by markoh1 on


Setup

var a = {}, b=[], num = 20000, lim = 10000;
  for (var i = 0; i < num; i++) {
    let v = {0:i, 1:i+1, 2:i+2, 3:i+3, 4:i+4, zz:'x'+i};
    a[1000+i] = v;
    b.push(v);
  }
  a[-1000] = {0:'50000', 1:1, 2:2, 3:3, 4:4, zz:'x'};
  a.x = {0:50001, 1:1, 2:2, 3:3, 4:4, zz:'y'};
  
  var filter = v => v[0]>lim, max = 500;
  function* filterMax(array, cb, count) {
      var i = 0;
      while (count) {
          while (i < array.length && !cb(array[i])) i++;
          if (i >= array.length) return;
          yield array[i++];
          count--;
      }
  }
  
  function* filterMax2(a, cb, count) {
      var c, j, i = 0, len = a.length;
      for (c=0; c<count; c++) {
          for (j=i; j<len; j++) {
              if (cb(a[i])) break;
              i++;
          }
          if (i >= len) return;
          yield a[i++];
      }
  }

Test runner

Ready to run.

Testing in
TestOps/sec
for in
var r = [];
for (let x in a) {
    //if (!a.hasOwnProperty(x)) continue;
    if (a[x][0] > lim) {
       r.push(a[x]);
       if (r.length>=max) break;
    }
}
ready
Object.values
Object.values(a).filter((v) => v[0] > lim)
ready
reduce
//Object.values(a).reduce((x,v) => x += v[0]>lim, 0)

var cnt=0;
Object.values(a).forEach(v => {
  if (v[0]>lim) cnt++;
});
ready
filter*
[...filterMax(Object.values(a), filter, max)]
ready
filter2*
[...filterMax(b, filter, max)]
//Object.values(a).length
//[...filterMax2(Object.values(a), filter, max)]
ready
classic
var r=[];
for (var i = 0; i < b.length; i++) {
    if (b[i][0] > lim) {
       r.push(b[i]);
       if (r.length>=max) break;
    }
}
ready

Revisions

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