preface

This article describes several array traversal methods commonly used JS and performance analysis comparison.

If this article is helpful to you, ❤️ attention + like ❤️ to encourage the author, the article public number first, pay attention to the front of nanjiu first time to get the latest article ~

Array methods

JavaScript development to now has provided many array methods, the following figure covers most of the array methods, this article mainly said the array traversal method, as well as their respective performance, so many methods, how to choose the best performance of the method for our development has a very big help.

Array traversal method

for

The standard for loop is the most traditional loop

var arr = [1.2.3.4.5]
for(var i=0; i<arr.length; i++){console.log(arr[i])
}
Copy the code

One of the simplest traversal, is also the most frequently used, better performance, but also can be optimized

Optimized version of the for loop statement

var arr = [1.2.3.4.5]
for(var i=0,len=arr.length; i<len; i++){console.log(arr[i])
}
Copy the code

Use temporary variables to cache the length to avoid fetching the array length repeatedly, especially if the array length is large.

This method is basically the highest performing of all looping methods

forEach

Ordinary forEach

Runs the given function on each element in an array, with no return value, often to traverse the elements

var arr5 = [10.20.30]
var result5 = arr5.forEach((item,index,arr) = >{
    console.log(item)
})
console.log(result5)
/* 10 20 30 undefined This method returns no value */
Copy the code

Arrays have built-in foreach loops that are used more frequently and actually perform worse than normal for loops

Prototype forEach

Because foreach comes with an Array, it is impossible to use it directly for things that are not of this type (such as NodeList), so it is possible to use this variant to make similar arrays have foreach functionality.

const nodes = document.querySelectorAll('div')
Array.prototype.forEach.call(nodes,(item,index,arr) = >{
  console.log(item)
})
Copy the code

Actual performance is weaker than normal foreach

for… in

Iterate through an object’s enumerable properties other than Symbol in any order, including inherited enumerable properties.

It is commonly used to iterate over objects, including names of non-integer types and properties above the inherited stereotype chain. Objects created using built-in constructors like Array and Object inherit the non-enumerable properties of Object.prototype and String.prototype and cannot be iterated.

var arr = [1.2.3.4.5]
for(var i in arr){
  console.log(i,arr[i])
}  // Where I is the object property, which is the index of the array
/** 0 1 1 2 3 3 4 4 5 **/
Copy the code

Most people like it, but it doesn’t perform very well, right

for… Of (cannot traverse objects)

Create an iteration loop on an iterable (with an Iterator interface) (Array, Map, Set, String, arguments), call a custom iteration hook, and execute a statement for the value of each different property, not iterating through the object

let arr=["Front end"."South nine"."ssss"];
    for (let item of arr){
        console.log(item)
    }
// Front-end NANjiu SSSS

// Iterate over the object
let person={name:"South nine".age:18.city:"Shanghai"}
for (let item of person){
  console.log(item)
}
// We found that this is not possible. We can use it with object.keys
for(let item of Object.keys(person)){
    console.log(person[item])
}
// Nanjiu 18 Shanghai
Copy the code

This approach is used in ES6 and performs better than Forin, but still not as well as normal for loops

map

Map: The array can only be traversed without interruption, and the return value is the modified array.

let arr=[1.2.3];
const res = arr.map(item= >{
  return res+1
})
console.log(res) / / / 2 and 4
console.log(arr) / / [1, 2, 3]
Copy the code

every

Run the given function on each item in the array and return true if the function returns true for each item

var arr = [10.30.25.64.18.3.9]
var result = arr.every((item,index,arr) = >{
      return item>3
})
console.log(result)  //false
Copy the code

some

For each of the given functions in the array, it returns true if one of the functions returns true, and false only if all of the functions return false

var arr2 = [10.20.32.45.36.94.75]
var result2 = arr2.some((item,index,arr) = >{
    return item<10
})
console.log(result2)  //false
Copy the code

reduce

The reduce() method performs a Reducer function (in ascending order) that you provide on each element in the array, summarizing its results into a single return value

const array = [1.2.3.4]
const reducer = (accumulator, currentValue) = > accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
Copy the code

filter

For each run of the given function in the array, an array of items that satisfy that function is returned

// filter returns a new array of items that meet the requirements
var arr3 = [3.6.7.12.20.64.35]
var result3 = arr3.filter((item,index,arr) = >{
    return item > 3
})
console.log(result3)  / /,7,12,20,64,35 [6]
Copy the code

The performance test

Tool to test

Using the tool to test the performance analysis results are shown below

Manual testing

We can also test with code ourselves:

// Test the function
function clecTime(fn,fnName){
        const start = new Date().getTime()
        if(fn) fn()
        const end = new Date().getTime()
        console.log(`${fnName}Execution time:${end-start}ms`)}function forfn(){
  let a = []
  for(var i=0; i<arr.length; i++){// console.log(i)
    a.push(arr[i])
  }
}
clecTime(forfn, 'for')   //for execution time :106ms

function forlenfn(){
  let a = []
  for(var i=0,len=arr.length; i<len; i++){ a.push(arr[i]) } } clecTime(forlenfn,'for len')   //for len execution time :95ms

function forEachfn(){
  let a = []
  arr.forEach(item= >{
    a.push[item]
  })
}
clecTime(forEachfn, 'forEach')   //forEach execution time :201ms

function forinfn(){
  let a = []
  for(var i in arr){
    a.push(arr[i])
  }
}
clecTime(forinfn, 'forin') // Forin execution time :2584ms

function foroffn(){
  let a = []
  for(var i of arr){
    a.push(i)
  }
}
clecTime(foroffn, 'forof') // ForOF execution time :221ms

/ /... The rest can be tested by themselves
Copy the code

Results analysis

Tool and manual tests found that the results were basically the same, array traversal method speed: traditional for loop is the fastest, for-in is the slowest

for-len > for > for-of > forEach > map > for-in

Recommended uses of javascript’s native traversal methods:

  • withforLoop through the array
  • withfor... inTraverse object
  • withfor... ofTraversal array objects (ES6)
  • withObject.keys()Gets a collection of object property names

Why the for… In will slow?

Because of the for… The in syntax is the first JavaScript statement that can iterate over an object key. Instead of looping over an array ([]), the engine does some extra work to keep track of properties that have been iterated over. Therefore, it is not recommended to use for… In to iterate over the array

Recommended reading

See how many of these browser interview questions you can answer? This is called call,apply,bind. This is called call,apply,bind

Think the article is good, you can click a like ah ^_^ plus welcome to pay attention to the comment exchange ~