binary insert vs sort

Benchmark created on


Setup

const size = 100_000;

function buildSortedArray() {
  return Array.from({ length: size }, (_, i) => ({
    _id: `task_${i}`,
    sendAtMs: i * 100
  }));
}

const maxMs = size * 100;
const arr1 = buildSortedArray();
const arr2 = buildSortedArray();

Test runner

Ready to run.

Testing in
TestOps/sec
binary insert
const arr = arr1;
  const task = { _id: `new`, sendAtMs: Math.floor(Math.random() * maxMs) };
  let left = 0;
  let right = arr.length;
  while (left < right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid].sendAtMs <= task.sendAtMs) {
      left = mid + 1;
    } else {
      right = mid;
    }
  }
  arr.splice(left, 0, task);

ready
.sort()
const arr = arr2;
  const task = { _id: `new`, sendAtMs: Math.floor(Math.random() * maxMs) };
  arr.push(task);
  arr.sort((a, b) => a.sendAtMs - b.sendAtMs);

ready

Revisions

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