for-in-testing

JavaScript performance comparison

Test case created by markoh1

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  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++];
      }
  }

};
</script>

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 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;
    }
}
pending…
Object.values
Object.values(a).filter((v) => v[0] > lim)
pending…
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++;
});
pending…
filter*
[...filterMax(Object.values(a), filter, max)]
pending…
filter2*
[...filterMax(b, filter, max)]
//Object.values(a).length
//[...filterMax2(Object.values(a), filter, max)]
pending…
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;
    }
}
pending…

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

0 Comments