obj vs arr iteration (v2)

Revision 2 of this benchmark created on


Description

If you have an object x, and you want to see which members are present, yet you know the set from which the members are drawn, is it faster to have an array of possible members,then check the object? Or simply iterate through the object? Conclusion: (Chrome/ff/saf) If the number of interesting values is greater than the typical number of attributes in the object in question, it's actually faster to start from the object's and search a map that describes the interesting values. This may only be practical if the interesting values are well understood enough to create a map at load time, and these results might not apply if one needs to construct that map.

Preparation HTML

<script>
  // Assume we have an object x, and a set of fields we're interested in. We need to find the intersection of the object fields, and this set of fields we're interested in. 
  // We can encode the set of fields we're interested in in a couple of ways. (An array or lookup map).
  // If we encode the fields of interest in an array, then we might think it is faster to start with the array, and search the object.
  // If we encode the fields we're interested in in an object map, then we could either look from that object map to x, or the other way around. This explores all possibilities.
  //This test tests both directions, and even uses a lookup map, which is assumed to have been set up, that describes what the content of the array is. (Should be faster than searching the entire array, 
  x = {something:1, somethingElse:2, another:'cat'}
  
  var arr =
  ['dog', 'cat', 'mom','dad','black','white','yellow','orange','purple'];
  var lookup =
  {'dog':true, 'cat':true, 'mom':true,'dad':true, 'black':true,'white':true,'yellow':true,'orange':true,'purple':true};
  
  var countFound = 0;
  
  
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
obj iteration
// You might either do this, or start from the lookup in the opposite direction. In this case x has fewer properties, so it's clear this would win, but if the interesting properties were much smaller than x's members, then we'd want to go the other way.
for(var key in x) {
    // do nothing
}
ready
arr iteration
for(var i = arr.length-1; i >=0; i--) {
   // do nothing
}
ready

Revisions

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