switch vs if (v2)

Revision 2 of this benchmark created on


Setup

const array = []
const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
const charLen = characters.length

for (let i = 0; i < 100000; i++) {
  const idx = Math.floor(Math.random() * charLen)

  array.push(characters[idx])
}

const arrayABC = ['a', 'b', 'c']
const arrayDEFG = ['d', 'e', 'f', 'g']
const arrayHIJKL = ['h', 'i', 'j', 'k', 'l']

const setABC = new Set(['a', 'b', 'c'])
const setDEFG = new Set(['d', 'e', 'f', 'g'])
const setHIJKL = new Set(['h', 'i', 'j', 'k', 'l'])

Test runner

Ready to run.

Testing in
TestOps/sec
for switch
let count = 0

for (let i = 0; i < 100000; i++) {
  switch (array[i]) {
    case 'a':
    case 'b':
    case 'c':
      count += 1
      break
    case 'd':
    case 'e':
    case 'f':
    case 'g':
      count += 2
      break
    case 'h':
    case 'i':
    case 'j':
    case 'k':
    case 'l':
      count += 3
      break
    default:
      count += 4
      break
  }
}

count
ready
for if
let count = 0
let temp = ''

for (let i = 0; i < 100000; i++) {
  temp = array[i]

  if (temp === 'a' || temp === 'b' || temp === 'c') count += 1
  else if (temp === 'd' || temp === 'e' || temp === 'f' || temp === 'g')
    count += 2
  else if (
    temp === 'h' ||
    temp === 'i' ||
    temp === 'j' ||
    temp === 'k' ||
    temp === 'l'
  )
    count += 3
  else count += 4
}

count
ready
for array includes
let count = 0

for (let i = 0; i < 100000; i++) {
  if (arrayABC.includes(array[i])) count += 1
  else if (arrayDEFG.includes(array[i])) count += 2
  else if (arrayHIJKL.includes(array[i])) count += 3
  else count += 4
}

count
ready
for set has
let count = 0

for (let i = 0; i < 100000; i++) {
  if (setABC.has(array[i])) count += 1
  else if (setDEFG.has(array[i])) count += 2
  else if (setHIJKL.has(array[i])) count += 3
  else count += 4
}

count
ready

Revisions

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