Find element in array (v3)

Revision 3 of this benchmark created on


Setup

const arr = new Array(1000000)
for (let i = 0; i < arr.length; i++){
	arr[i] = i + 1
}
arr.sort((a,b) => a - b)
const el = Math.floor(Math.random() * arr.length)

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
}
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
}
searchElement(arr, el)
ready
find
const searchElement =(arr, el) => {
    const res = arr.find((val) => val === el)
    if (res === undefined){
        return -1
    }
    return res
}
searchElement(arr, el)
ready

Revisions

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