lookup: for vs includes vs set vs object vs map

Benchmark created on


Setup

// Based on https://jsbench.me/3pkjlwzhbr/1

var theArr = Array.from({ length: 100 }, (_, el) => el)
var theSet = new Set(theArr)
var theObject = Object.assign({}, ...theArr.map(num => ({ [num]: true })))
var theMap = new Map(theArr.map(num => [num, true]))

var theTarget = 50


// Array

function isTargetThereFor(arr, target) {
  const len = arr.length
  for (let i = 0; i < len; i++) {
    if (arr[i] === target) {
      return true
    }
  }
  return false
}
function isTargetThereForReverse(arr, target) {
  const len = arr.length
  for (let i = len; i > 0; i--) {
    if (arr[i] === target) {
      return true
    }
  }
  return false
}

function isTargetThereIncludes(arr, target) {
  return arr.includes(target)
}

function isTargetThereIndexOf(arr, target) {
	return arr.indexOf(target)
}

// Set

function isTargetThereSet(numberSet, target) {
  return numberSet.has(target)
}

// Object 

function isTargetThereHasOwnProperty(obj, target) {
  return obj.hasOwnProperty(target)
}
function isTargetThereIn(obj, target) {
  return target in obj
}
function isTargetThereSelectKey(obj, target) {
  return obj[target]
}

// Map

function isTargetThereMap(numberMap, target) {
  return numberMap.has(target)
}

Test runner

Ready to run.

Testing in
TestOps/sec
For Loop
var forLoop = isTargetThereFor(theArr, theTarget);
ready
For Loop reverse
var forLoopReverse = isTargetThereForReverse(theArr, theTarget);
ready
array.includes(target)
var includes = isTargetThereIncludes(theArr, theTarget);
ready
array.indexOf(target)
var indexof = isTargetThereIndexOf(theArr, theTarget)
ready
set.has(target)
var setHas = isTargetThereSet(theSet, theTarget);
ready
obj.hasOwnProperty(target)
var hasOwnProperty = isTargetThereHasOwnProperty(theObject, theTarget);
ready
target in obj
var keyIn = isTargetThereIn(theObject, theTarget);
ready
obj[target]
var propertyIn = isTargetThereSelectKey (theObject, theTarget);
ready
map.has(target)
var mapHas = isTargetThereMap(theMap, theTarget);
ready

Revisions

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