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

后端 未结 7 1924
逝去的感伤
逝去的感伤 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 04:00

    indexOf does a bunch of type-checking and validation that the for loop and while loop ignore.

    Here's the indexOf algorithm:

    https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

    Edit: My guess is indexOf is faster for big arrays because it caches the length of the array before looping through it.

提交回复
热议问题