Finding an object in an array vs object hash (v2)

Revision 2 of this benchmark created by Scott Wolchok on


Description

A simple performance test to see how object keys compares against finding any object in an array using array.indexOf versus object[key]

Setup

var _nextObjectID = 0;
    
    function MyObject() {
      this.ID = _nextObjectID + '';
      _nextObjectID++;
    }
    var _array = [];
    var _hash = {};
    var _arraySmall = [];
    var _hashSmall = {};
    
    var obj = null;
    for (var i = 0; i < 10000; i++) {
      obj = new MyObject();
      _array.push(obj);
      _hash[obj.ID] = obj;
      if (i < 10) {
        _arraySmall.push(obj);
        _hashSmall[obj.ID] = obj;
      }
    }
    
    //Randomly select the object we will be looking for
    var _objID = Math.round(Math.random() * _nextObjectID);
    var _findObject = _array[_objID];
    var _objIDSmall = Math.round(Math.random() * 9);
    var _findObjectSmall = _arraySmall[_objIDSmall];

Test runner

Ready to run.

Testing in
TestOps/sec
array.indexOf(obj)
_array.indexOf(_findObject);
ready
object[id]
//Use the object ID to pull it from the hash
var id = _findObject.ID;
_hash[id];
ready
small array indexOf
_arraySmall.indexOf(_findObjectSmall);
ready
small hash
var id = _findObjectSmall.ID;
_hashSmall[id];
ready

Revisions

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

  • Revision 1: published by Dino Gambone on
  • Revision 2: published by Scott Wolchok on