Find an element array method performance comparison

    const arr = []
    for(let i=0; i<1000000; i++) {
      arr.push(`ahdgd${i}`)
    }
    console.time('indexOf')
    arr.indexOf('ahdgd10000')
    console.timeEnd('indexOf')
    // indexOf: 0.0400390625ms
    
    console.time('includes')
    arr.includes('ahdgd10000')
    console.timeEnd('includes')
    // includes: 0.025146484375ms

    console.time('hasOwnProperty')
    arr.hasOwnProperty('ahdgd10000')
    console.timeEnd('hasOwnProperty')
    // hasOwnProperty: 0.004150390625ms

Practice can be seen by the above arr.hasOwnProperty () method much faster.

Whether arr.indexOf () or es6 of arr.includes (), all through the array in nature

hasOwnProperty() Method returns a Boolean value indicating that the object 's own property has the specified attribute (that is, whether there are specific key) which will ignore those inherited from the prototype chain to the property.

Arrays are objects, the array element corresponding to the value of the existing building and the corresponding subscript values.

Guess you like

Origin blog.csdn.net/qq_41831345/article/details/93618330