search

Benchmark created on


Setup

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function binarySearch(arr, target) {
  let low = 0;
  let high = arr.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);

    if (arr[mid] === target) {
      return mid;
    } else if (arr[mid] < target) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }

  return -1; // Target not found
}

const MAX = 10_000_000;
const array = new Array(MAX).keys().toArray();

const x = getRandomInt(0, MAX);
const y = getRandomInt(0, MAX);
const int = getRandomInt(Math.min(x, y), Math.max(x, y))

Test runner

Ready to run.

Testing in
TestOps/sec
linear search
array.find(n => n === int);
ready
for loop
for (let i = 0; i < array.length; i++) {
	if (array[i] === int) {
		break;
	}
}
ready
binary search
binarySearch(array, int);
ready

Revisions

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