Why is looping through an Array so much faster than JavaScript\'s native indexOf? Is there an error or something that I\'m not accounting for? I expected nati
We can trust to a plain for loop at every single time.
I wrote the code below to discover the answer of this question. It is also runnable.
It shows that plain for loop is the best solution when considering performance.
(The code also can be found on jsfiddle)
console.clear()
let a = []
// populating array data
for (let i = 0; i < 100000; i++) {
a.push(i)
}
let testNum = 90000
let found
let totalMS4ForLoop = 0
let totalMS4IndexOf = 0
let start
let end
// simulating 10000 requests which are come consecutively
for (o = 0; o < 10000; o++) {
start = Date.now()
for (let i = 0; i < a.length; i++) {
if (a[i] == testNum) { found = a[i]; break }
}
end = Date.now()
totalMS4ForLoop += end - start
start = Date.now()
found = a[a.indexOf(testNum)]
end = Date.now()
totalMS4IndexOf += end - start
}
console.log("10000 for-loop executions took total " + totalMS4ForLoop + " ms.")
console.log("10000 indexOf executions took total " + totalMS4IndexOf + " ms.")