obj vs arr iteration

Benchmark created by jordo on


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) {
    if(!x.hasOwnProperty(key)) {continue;}
   if(lookup[key]) {
     countFound++;
   }
}
ready
arr iteration
for(var i = arr.length-1; i >=0; i--) {
   if(x[arr[i]]) {
      countFound++;
   }
}
ready

Revisions

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