当前位置:网站首页>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
边栏推荐
- 喜讯!瑞云科技被授予“海上扬帆”5G融合应用专委会成员单位
- pd.melt() vs reshape2::melt()
- uniapp滚动条置顶效果、自定义页面滚动条的位置(整理)
- LeetCode 101. 对称二叉树 && 100. 相同的树 && 572. 另一棵树的子树
- C语言 整数与字符串的相互转换
- List conversion problem
- Introduction to cloud XR and development opportunities of cloud XR in 5g Era
- 图的相关操作
- ORB_ Slam3 recurrence - Part I
- 一周活动速递|深入浅出第8期;Meetup成都站报名进行中
猜你喜欢

ORB_ Slam3 recurrence - Part I

C language -- 25 minesweeping game

How to choose digital twin visualization platform

工程师必看的示波器探头安全使用说明书

Thales launches solutions to help SAP customers control cloud data

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

柔性电流探头选型指南

MySQL 索引优化全攻略

Related operations of binary tree

imx6 RTL8189FTV移植
随机推荐
tkinter GUI版通信录管理系统
云VR:虚拟现实专业化的下一步
[QNX Hypervisor 2.2用户手册]9.4 dryrun
越来越成熟的Rust,都应用了哪些场景呢?
Recognized by international authorities! Oceanbase was selected into the Forrester translational data platform report
NC68 跳台阶
Could not stop Cortex-M device! Please check the JTAG cable solution
BL602 开发环境搭建
C language libcurl cross compilation
Connect to MySQL using sqldeveloper
nodejs 简单例子程序之express
Auditing related notes
pd.melt() vs reshape2::melt()
泛域名配置方法
如何判断静态代码质量分析工具的性能?这五大因素必须考虑
想要做好软件测试,可以先了解AST、SCA和渗透测试
imx6 RTL8189FTV移植
浅析回归问题、建模、预测
srec_cat 常用参数的使用
图的相关操作