0

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:

result1 result2 result3

David Chan
  • 641
  • 1
  • 7
  • 10
  • Please don't turn into one of these people who put random stuff on JSPerf, or time their functions in some odd way, get some numbers, then say way A is 20% better than way B. – ASDFGerte Oct 05 '19 at 02:00
  • Ah, microbenchmarks. (As to which is faster—it depends. `forEach` used to be *slower* than `for`, although that’s changed relatively recently.) – Dave Newton Oct 05 '19 at 02:02
  • Then how can I know which way is faster? – David Chan Oct 05 '19 at 03:15

0 Answers0