First, I want to thanks to Bails for his answer on question console.time shows different time running the same function. But it still confusing me that how can I compare running time of two different functions
Here's the code I have tried.
function fun1(arr) {
let a = 0
for(let i = 0;i < arr.length; i++) {
a += arr[i]
}
return a
}
function fun2(arr) {
let a = 0
arr.forEach((v) => {
a += v
})
return a
}
let array = []
for(let i = 0;i < 100; i++) {
array.push(Math.random())
}
console.time('fun1')
fun1(array)
console.timeEnd('fun1')
console.time('fun2')
fun2(array)
console.timeEnd('fun2')
We all know that forEach is faster than for. But when I run the code above, I got different results: