Multiple OR vs. Array#indexOf vs. x in {} (v2)

Revision 2 of this benchmark created by unscriptable on


Description

I think we can all agree this pattern is sexy, but how well does it perform?

Note that this assumes that Array#indexOf is available, which may not be the case in old browsers.

Setup

var foo = 42,
        x = 1,
        y = 2,
        z = 42,
        arr1 = [x, y],
        arr2 = [x, y, z],
        obj1 = {x: 1, y: 1},
        obj2 = {x: 1, y: 1, z: 1};

Test runner

Ready to run.

Testing in
TestOps/sec
Multiple ||, no match
if (foo === x || foo === y) {
  // code goes here
}
ready
Array#indexOf, no match
if (~arr1.indexOf(foo)) {
  // code goes here
}
ready
Multiple ||, match
if (foo === x || foo === y || foo === z) {
  // code goes here
}
ready
Array#indexOf, match
if (~arr2.indexOf(foo)) {
  // code goes here
}
ready
x in {}, no match
if (foo in obj1) {
  // code goes here
}
ready
x in {}, match
if (foo in obj2) {
  // code goes here
}
ready

Revisions

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

  • Revision 1: published by Mathias Bynens on
  • Revision 2: published by unscriptable on