Find element in array

Benchmark created on


Setup

const arr = new Array(1000000)
for (let i = 0; i < arr.length; i++){
	arr[i] = i + 1
}

Test runner

Ready to run.

Testing in
TestOps/sec
linear
const searchElement = (arr, el) => {
    for (let i = 0; i<arr.length; i++){
        if (arr[i] === el){
            return arr[i]
        }
    }
    return -1
}
const el = Math.floor(Math.random() * arr.length)
searchElement(arr, el)
ready
bin-search
const searchElement = (arr, el) => {
    let left = -1
    let right = arr.length
    while (right - left > 1){
        const mid = Math.floor((left + right) /2)
        if (arr[mid] === el) return arr[mid]
        arr[mid] > el ? right = mid : left = mid
    }

    return -1
}
const el = Math.floor(Math.random() * arr.length)
searchElement(arr, el)
ready
find
const searchElement =(arr, el) => {
    const res = arr.find((val) => val === el)
    if (res === undefined){
        return -1
    }
    return res
}
const el = Math.floor(Math.random() * arr.length)
searchElement(arr, el)
ready

Revisions

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