Skip to content

Instantly share code, notes, and snippets.

@flcoder
Last active December 27, 2020 06:26
Show Gist options
  • Save flcoder/5fa34762ccdf34eab4de7b8c8bc4f2e6 to your computer and use it in GitHub Desktop.
Save flcoder/5fa34762ccdf34eab4de7b8c8bc4f2e6 to your computer and use it in GitHub Desktop.
const NUM_OPS = 300000
const NUM_ELS = 100
const ops = [] 
const {random, floor} = Math

let arr, set

for(let i = 0; i < NUM_OPS; ++i) ops.push([random() < 0.5, floor(random()*NUM_ELS)])

for(let test of [with_splice, with_pop, with_set]) {
  arr = []
  set = new Set
  console.time(test.name)
  for(let op of ops) test(...op)
  console.timeEnd(test.name)
}

function with_splice(o, e) {
  if(o) {
    arr.push(o)
  } else {
    const index = arr.indexOf(e)
    if(index > -1) arr.splice(index, 1)
  }
}

function with_pop(o, e) {
  if(o) {
    arr.push(o)
  } else {
    const index = arr.indexOf(e)
    if(index > -1) {
      arr[index] = arr[arr.length-1]
      arr.pop()
    }
  }
}
 
function with_set(o, e) {
  o ? set.add(e) : set.delete(e)
}

My results on Node:

with_splice: 6978.000ms
with_pop:    6912.000ms
with_set:      17.195ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment