filter in js

Benchmark created on


Setup

const ARR_SMALL = [...Array(10)].map((_, idx) => idx)
const PIVOT_SMALL = 7

const ARR_BIG = [...Array(10_000_000)].map((_, idx) => idx)

const PIVOT_BIG = 7_000_000



function filter_unstable(arr, item) {
  const index = arr.indexOf(item);
  if (index === -1) {
    return;
  }
  const stop = arr.length - 1;
  arr[index] = arr[stop];
  arr.pop();
}

function filter_stable(arr, item) {
  let index = arr.indexOf(item);
  if (index === -1) {
    return;
  }
  const stop = arr.length - 1;
  while (index < stop) {
    arr[index] = arr[++index];
  }
  arr.pop();
}

Test runner

Ready to run.

Testing in
TestOps/sec
std (small)
[...ARR_SMALL].filter((thing) => thing === PIVOT_SMALL)
ready
stable (small)
filter_stable([...ARR_SMALL], PIVOT_SMALL)
ready
unstable (small)
filter_unstable([...ARR_SMALL], PIVOT_SMALL)
ready
std (big)
[...ARR_BIG].filter((thing) => thing === PIVOT_BIG)
ready
stable (big)
filter_stable([...ARR_BIG], PIVOT_BIG)
ready
unstable (big)
filter_unstable([...ARR_BIG], PIVOT_BIG)
ready

Revisions

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