JS array loop method and efficiency analysis comparison

JS array loop method and efficiency analysis comparison

Array Methods

JavaScript has provided many array methods. The following figure covers most of the array methods. This article mainly talks about array traversal methods and their respective performance. With so many methods, how to choose the method with the best performance is of great help to our development.

Array traversal methods

for

  • The standard for loop statement is also the most traditional loop statement
var arr = [1,2,3,4,5]
for(var i=0;i<arr.length;i++){
  console.log(arr[i])
}

The simplest traversal method is also the most frequently used, with good performance, but it can be optimized

  • Optimized for loop statement
var arr = [1,2,3,4,5]
for(var i=0,len=arr.length;i<len;i++){
  console.log(arr[i])
}

Use temporary variables to cache the length to avoid repeatedly obtaining the array length. The optimization effect will be more obvious especially when the array length is large.

This method is basically the most performant of all loop traversal methods.

forEach

  • Normal forEach

Runs a given function on each element in an array. It has no return value and is often used to traverse 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 has no return value*/

The foreach loop that comes with the array is used frequently, but its performance is actually weaker than the ordinary for loop.

  • Prototype forEach

Since foreach is a built-in function of the Array type, it cannot be used directly for some non-Array types (such as NodeList), so this variant is created. Using this variant can give similar arrays the foreach function.

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

The actual performance is weaker than ordinary foreach

for...in

Iterates over an object's enumerable properties other than Symbol in any order, including inherited enumerable properties.

It is generally used to traverse objects, including names of non-integer types and inherited properties on the prototype chain can also be traversed. Objects created using built-in constructors like Array and Object will inherit the non-enumerable properties of Object.prototype and String.prototype and cannot be traversed.

var arr = [1,2,3,4,5]
for(var i in arr){
  console.log(i,arr[i])
} //Here i is the object attribute, that is, the subscript of the array/**
0 1
1 2
twenty three
3 4
4 5 **/

Most people like to use this method, but its performance is not very good

for...of (cannot traverse objects)

Create an iteration loop on an iterable object (with iterator interface) (Array, Map, Set, String, arguments), call the custom iteration hook, and execute statements for each different attribute value. Do not traverse the object.

let arr=["front end","南玖","ssss"];
    for (let item of arr){
        console.log(item)
    }
//Front-end Nanjiu ssss

//Traverse the object let person={name:"南玖",age:18,city:"上海"}
for (let item of person){
  console.log(item)
}
// We found that it is not possible. We can use it with Object.keys for(let item of Object.keys(person)){
    console.log(person[item])
}
// Nanjiu 18 Shanghai

This method is used in es6, and its performance is better than forin, but still not as good as the ordinary for loop.

map

map: can only traverse the array without interruption, and the return value is the modified array.

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

every

Runs the given function on each item in the array. If the function returns true for every item, then the function returns true.

var arr = [10,30,25,64,18,3,9]
var result = arr.every((item,index,arr)=>{
      return item>3
})
console.log(result) //false

some

Run the given function for each item in the array. If one of the items in the function returns true, it returns true. If all items return false, it returns false.

var arr2 = [10,20,32,45,36,94,75]
var result2 = arr2.some((item,index,arr)=>{
    return item<10
})
console.log(result2) //false

reduce

The reduce() method executes a reducer function you provide for each element in the array (in ascending order), summarizing the 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));

filter

Running a given function on each item in an array returns an array of items that satisfy the function.

// filter returns a new array consisting of array 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) //[6,7,12,20,64,35]

Performance testing tool testing

The results of the performance analysis using the tool test are shown in the figure below

Manual Testing

We can also test the code ourselves:

//Test 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 (outrageous)

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 yourself

Results Analysis

After tool and manual testing, the results are basically the same. The speed of array traversal methods is: the traditional for loop is the fastest, and for-in is the slowest.

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

Suggested usage of javascript native traversal methods:

  • Iterating over an array with a for loop
  • Iterating over objects with for...in
  • Iterating over array-like objects with for...of (ES6)
  • Use Object.keys() to get a collection of object attribute names

Why is for...in slow?

Because the for...in syntax is the first JavaScript statement capable of iterating over object keys, looping over object keys ({}) is different from looping over arrays ([]), and the engine does some extra work to keep track of which properties have been iterated over. Therefore, it is not recommended to use for...in to traverse the array

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Summary of several common methods of JavaScript arrays
  • A brief discussion on the built-in traversal methods of JS arrays and their differences
  • Detailed explanation of the difference between javascript array traversal for and for in
  • Javascript array and dictionary usage and object attribute traversal skills
  • JS array and object traversal method code summary

<<:  Nginx solves cross-domain issues and embeds third-party pages

>>:  Use button trigger events to achieve background color flashing effect

Recommend

Solution to the problem of insufficient storage resource pool of Docker server

Table of contents 1. Problem Description 2. Probl...

Details of various font formats in HTML web pages

This section starts with the details of text modi...

Example of using nested html pages (frameset usage)

Copy code The code is as follows: <!DOCTYPE ht...

Vue implements simple slider verification

This article example shares the implementation of...

Detailed tutorial on installing ElasticSearch 6.x in docker

First, pull the image (or just create a container...

Detailed explanation of the use of Vue image drag and drop zoom component

The specific usage of the Vue image drag and drop...

Summary of various forms of applying CSS styles in web pages

1. Inline style, placed in <body></body&g...

Mobile Internet Era: Responsive Web Design Has Become a General Trend

We are in an era of rapid development of mobile In...

Use vertical-align to align input and img

Putting input and img on the same line, the img ta...

JS realizes automatic playback of timeline

Recently, I have implemented such an effect: clic...

mysql8.0.23 msi installation super detailed tutorial

1. Download and install MySql Download MySql data...

The best solution for implementing digital plus and minus buttons with pure CSS

Preface: For the implementation of digital additi...

JS achieves five-star praise effect

Use JS to implement object-oriented methods to ac...

WeChat applet implements search box function

This article example shares the specific code for...

A brief discussion on the Linux kernel's support for floating-point operations

Currently, most CPUs support floating-point units...