Why is looping through an Array so much faster than JavaScript's native `indexOf`?

后端 未结 7 1901
逝去的感伤
逝去的感伤 2020-11-29 03:15

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

7条回答
  •  死守一世寂寞
    2020-11-29 03:52

    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.")

提交回复
热议问题