indexOf vs. object (just text) (v3)

Revision 3 of this benchmark created on


Description

This test was made to benchmark lookups of string-typed key in arrays and objects. (Especially important to choose which container is more suitable for implementing Set and other containers with unique keys).

Preparation HTML

<script>
  function getGarbage(seed, salt) {
    salt = salt || 154864;
    seed = salt * seed;
  
    var result = '';
    var vocabulary = new String('az');
    var chBase = vocabulary.charCodeAt(0);
    var chLen = vocabulary.charCodeAt(1) - vocabulary.charCodeAt(0) + 1;
  
    while (seed > 0) {
      code = seed % chLen; // from Russia, with love
      result += String.fromCharCode(code + chBase);
      seed = (seed / chLen) | 0;
    }
    return result;
  }
  
  function makeKey(i, salt) {
    return getGarbage(i, salt);
  }
  
  function generate(count, salt) {
    var arr = [];
    var obj = {};
    for (var i = count; i > 0; --i) {
      var r = makeKey(Math.random() * count | 0, salt);
      arr.push(r);
      obj[r] = true;
    }
    return {
      'array': arr,
      'object': obj,
      'searchFor': makeKey(Math.random() * count | 0, salt)
    };
  }
  
  function testObject(iCase) {
    var s = samples[iCase];
    return s.object[s.searchFor];
  }
  
  function testArray(iCase) {
    var s = samples[iCase];
    return s.array.indexOf[s.searchFor] != -1;
  }
  
  var maxN = 100 * 100 * 10;
  var samples = [
  generate(100), generate(100 * 100), generate(maxN)];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Object [100]
testObject(0)
ready
Object [10'000]
testObject(1)
ready
Object[100'000]
testObject(2)
ready
Array[100]
testArray(0)
ready
Array[10'000]
testArray(1)
ready
Array[100'000]
testArray(2)
ready

Revisions

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