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