for-in object vs keys vs cache

Benchmark created by John M on


Description

Given an object that comes in:

<span class="kw2">var</span> map <span class="sy0">=</span> <span class="br0">{</span> <span class="st0">'key'</span><span class="sy0">:</span> <span class="st0">'value'</span><span class="sy0">,</span> ... <span class="br0">}</span><span class="sy0">;</span>

How expensive is it to iterate over the keys using different techniques?

Setup

// Hardcoded map of 9 keys. It's not mutated. This roughly matches the intended use case.
    var map = { a: 1, b: '2', c: null, d: [4], e: {f: 56}, g: 7, h: 8, i: 9, j: 10 };
    
    var cachedKeys = Object.keys(map);
    
    // The number of keys with truthy values
    var expectedCount = 8;

Test runner

Ready to run.

Testing in
TestOps/sec
for-in to enumerate keys
var count = 0;
for (var key in map) {
  // do something non-trivial
  if (map[key]) count++;
}
if (count != expectedCount) throw 'bad result';
ready
Object.keys
var count = 0;
var keys = Object.keys(map);
for (var i = 0, len = keys.length; i < len; i++) {
  // do something non-trivial
  if (map[keys[i]]) count++;
}
if (count != expectedCount) throw 'bad result';
ready
cached keys
var count = 0;
var keys = cachedKeys;
for (var i = 0, len = keys.length; i < len; i++) {
  // do something non-trivial
  if (map[keys[i]]) count++;
}
if (count != expectedCount) throw 'bad result';
ready

Revisions

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

  • Revision 1: published by John M on