当前位置:网站首页>What are the methods of traversing arrays? What is the difference between the performance of the for loop foreach for/in for/of map and how to choose?
What are the methods of traversing arrays? What is the difference between the performance of the for loop foreach for/in for/of map and how to choose?
2022-07-25 18:21:00 【Cherry pill peach】
List of articles
Preface
JavaScript Up to now, many array methods have been provided , Let's talk about the traversal method of arrays , And their respective performance , There are so many ways , How to choose the best performance method is very helpful to our development .
- What are the traversal methods of arrays ?
for loop ,forEach,for…in,for…of,map,every,some,reduce,filter - Is there any difference in their performance ?
for > for-of > forEach > map > for-in
Tips : The following is the main body of this article , The following cases can be used for reference
Array traversal method
1. for
The simplest and most commonly used A traversal method
var arr = [a,b,c,d,e];
for (var i=0, len=arr.length; i<len; i++ ) {
console.log(arr[i]);
}
This method is basically the highest performance of all loop traversal methods
2. forEach
Run the given function for each element in the array , no return value , Often used to traverse elements
var arr = [a,b,c];
var fun = arr.forEach((item,index,arr)) => {
console.log(item)
}
console.log(fun)
/* a b c undefined The method does not return a value Array comes with forEach loop , High frequency of use , The actual performance is better than ordinary for Weak circulation
3. for…in
Traverse an object in any order except Symbol Enumerable properties other than , Include inherited enumerable properties .
Commonly used to traverse objects , The properties above the prototype chain, including the names of non integer types and inheritance, can also be traversed . image Array and Object Objects created with built-in constructors inherit from Object.prototype and String.prototype The enumerable property of cannot be traversed .
var arr = [a,b,c,d,e];
for (var i in arr) {
console.log(i,arr[i]);
} // there i It's an object property , That is, the subscript of an array
/* 0 a 1 b 2 c 3 d 4 e */
Many people like to use this method , But its performance is not very good
4. for…of( Can't traverse object )
In iteratable objects ( have iterator Interface )(Array,Map,Set,String,arguments) Create an iteration loop on , Call the custom iteration hook , And execute statements for the values of different attributes , Can't traverse object
let arr=["apple","orange","peach"];
for (let item of arr){
console.log(item)
}
//apple orange peach
// Traversing objects
let person={
name:"apple",age:18,city:" Shanghai "}
for (let item of person){
console.log(item)
}
// We found it impossible We can match Object.keys Use
for(let item of Object.keys(person)){
console.log(person[item])
}
// apple 18 Shanghai
This way is es6 It's used in , Better performance than for…in, But it's still not as common as for loop
5. map
map: Only arrays can be traversed , Don't interrupt , 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]
6. every
Run the given function for each in the array , If the function returns... For each item true, Then the function returns true
var arr = [1,2,3,4,5,6,7];
var fun = arr.some((item,index,arr) => {
return item<1
})
console.log(fun) //false
7. reduce
reduce() Method to execute a... Provided by you for each element in the array reduce function ( Ascending execution ), Summarize 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));
8. filter
Run the given function on each of the arrays , Will return an array of items that satisfy the function
// filter Returns a new array 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 analysis
// Test functions
function clecTime(fn,fnName){
const start = new Date().getTime()
if(fn) fn()
const end = new Date().getTime()
console.log(`${
fnName} Execution time consuming :${
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 consuming :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 consuming :95ms
function forEachfn(){
let a = []
arr.forEach(item=>{
a.push[item]
})
}
clecTime(forEachfn, 'forEach') //forEach Execution time consuming :201ms
function forinfn(){
let a = []
for(var i in arr){
a.push(arr[i])
}
}
clecTime(forinfn, 'forin') //forin Execution time consuming :2584ms ( Out of line )
function foroffn(){
let a = []
for(var i of arr){
a.push(i)
}
}
clecTime(foroffn, 'forof') //forof Execution time consuming :221ms
// ... Others can be tested by themselves
Result analysis :
for > for-of > forEach > map > for-in
JavaScript Recommended usage of native traversal methods :
- use for Loop through groups
- use for…in Traversing objects
- use for…of Traversing class array objects (ES6)
- use Object.keys() Gets the collection of object property names
边栏推荐
猜你喜欢

Auditing相关注解

想要做好软件测试,可以先了解AST、SCA和渗透测试

软件测试——常用的测试工具

Good news! Ruiyun technology was awarded the member unit of 5g integrated application special committee of "sailing on the sea"

大话DevOps监控,团队如何选择监控工具?

Could not stop Cortex-M device! please check the JTAG cable的解决办法
![Why is the index in [mysql] database implemented by b+ tree? Is hash table / red black tree /b tree feasible?](/img/1f/a2d50ec6bc97d52c1e7566a42e564b.png)
Why is the index in [mysql] database implemented by b+ tree? Is hash table / red black tree /b tree feasible?

tkinter GUI版通信录管理系统

ORB_ Slam3 recurrence - Part I

LeetCode 101. 对称二叉树 && 100. 相同的树 && 572. 另一棵树的子树
随机推荐
使用sqldeveloper连接mysql
"Digital security" alert NFT's seven Scams
Repair process of bad blocks of primary standby database
Stm32f105rbt6 internal flash debugging
BiSeNet v1
Basic operation of bidirectional linked list
NC15 求二叉树的层序遍历
CH582 BLE 5.0 使用 LE Coded 广播和连接
电流探头在ECU、电气系统电流测量的应用
NC68 跳台阶
Taishan Office Technology Lecture: conversion relations of inch, centimeter, pound, pika, Ti, line, word line and pixel
泛域名配置方法
Cloud VR: the next step of virtual reality specialization
C language libcurl cross compilation
"Jargon" | what kind of experience is it to efficiently deliver games with Devops?
Auditing related notes
Linux启动mysql报错
Leetcode 101. symmetric binary tree & 100. same tree & 572. Subtree of another tree
The new version of 3dcat v2.1.3 has been released. You can't miss these three function updates!
NC78 反转链表