check, if list contains element

Benchmark created by fishbone on


Description

Given, two different ways of storing elements in a list:

  • Array-items: ["a", "b"]
  • Object-keys: {"a": true, "b": true}

Finding a specific item in an array:

  • for-loop which breaks when item is found (test 1)
  • using indexOf and check, whether result is greater than -1 (test 2)

When using objects as demonstrated above, we can simply use the item-accessor (test 3)

The Javascript engine has to traverse the scope chain in the object-case. Therefore I assumed similar results for tests 2 and 3.

Test 4-6 search for random items, in order to prevent browsers from returning cached results.

Preparation HTML

<script>
  var MAX_LENGTH = 9999;
  
  var u = {};
  var v = [];
  
  function item() {
   return parseInt(MAX_LENGTH / 2) * 1.3;
  };
  
  function randItem() {
   return parseInt(Math.random() * MAX_LENGTH) * 1.3;
  }
  for (var i = 0; i < MAX_LENGTH; ++i) {
   u[i * 1.3] = true;
   v.push(i * 1.3);
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
array: for-loop
var len = v.length,
    j;
for (j = 0; j < len; ++j) {
 if (v[j] === item()) break;
}
ready
array: indexOf
v.indexOf(item()) > -1
ready
object: accessor
u[item()] !== undefined
ready
array: for-loop (random item)
var len = v.length,
    j, it = randItem();
for (j = 0; j < len; ++j) {
 if (v[j] === it) break;
}
ready
array: indexOf (random item)
v.indexOf(randItem()) > -1
ready
object: accessor (random item)
u[randItem()] !== undefined
ready

Revisions

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