Array Search vs. Bitmask Search (v2)

Revision 2 of this benchmark created on


Description

Test for presence of multiple values in an array. First, using Array.indexOf(). Second, using a bitmask.

Preparation HTML

<script>
  // Array setup
  var haystack1 = ["a", "b", "c", "d", "e"];
  var needles1 = ["a", "c", "e"];

  // Bitmask setup
  var opts = {
    "a": 1,
    "b": 2,
    "c": 4,
    "d": 8,
    "e": 16,
    "f": 32,
    "g": 64,
    "h": 128
  };
  var haystack2 = opts.a | opts.b | opts.c | opts.d | opts.e;
  var needles2 = opts.a | opts.c | opts.e;

  var haystack3 = {};
  haystack3[opts.a] = true;
  haystack3[opts.b] = true;
  haystack3[opts.c] = true;
  haystack3[opts.d] = true;
  haystack3[opts.e] = true;

  var needles3 = {};
  needles3[opts.a] = true;
  needles3[opts.c] = true;
  needles3[opts.e] = true;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Array search
function contains(haystack, needles) {
  for (var i = 0, len = needles.length; i < len; i++) {
    if (haystack.indexOf(needles[i]) === -1) {
      return false;
    }
  }
  return true;
}

contains(haystack1, needles1);
ready
Bitmask search
function contains(haystack, needles) {
  return (haystack & needles) >= needles;
}

contains(haystack2, needles2);
ready
Object lookup
function contains(haystack, needles) {
  for (var prop in needles) {
    if (!needles.hasOwnProperty(prop)) {
      continue;
    }
    if (haystack[prop]) {
      return true;
    }
  }
  return false;
}

contains(haystack3, needles3);
ready

Revisions

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