当前位置:网站首页>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
边栏推荐
- STM8S003F3 内部flash调试
- BiSeNet v1
- List conversion problem
- 遍历数组的方法有哪些?for循环 forEach for/in for/of map的性能又有什么差别 该如何选择?
- C盘空间不够 mklink解决VScode扩展迁移到其他盘
- srec_cat 常用参数的使用
- 1--- electronic physical cognition
- 11.2-HJ86 求最大连续bit数
- Sequential storage structure, chain storage structure and implementation of stack
- Use of LCD screen of kendryte k210 on FreeRTOS
猜你喜欢

数二2010真题考点

使用sqldeveloper连接mysql

Update 3dcat real time cloud rendering V2.1.2 release

【网页性能优化】SPA(单页面应用)首屏加载速度慢怎么办?

win11下vscode 自动升级失败 There was an error while marking a file for deletion

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

How to judge the performance of static code quality analysis tools? These five factors must be considered

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

如何判断静态代码质量分析工具的性能?这五大因素必须考虑

imx6 RTL8189FTV移植
随机推荐
对角化、A的幂
"Digital security" alert NFT's seven Scams
C盘空间不够 mklink解决VScode扩展迁移到其他盘
Leetcode 101. symmetric binary tree & 100. same tree & 572. Subtree of another tree
浅析回归问题、建模、预测
Connect to MySQL using sqldeveloper
Unittest framework application
C语言 整数与字符串的相互转换
Design practice of Netease strictly selecting inventory center
Optimistic lock pessimistic lock applicable scenario
Li Kai: the interesting and cutting-edge audio and video industry has always attracted me
乐观锁解析
Number two 2010 real test site
GAN的详细介绍及其应用(全面且完整)
STM32F105RBT6 内部flash调试
3DCAT v2.1.3新版本发布,这三大功能更新你不容错过!
Polynomial addition
List conversion problem
Today's sleep quality record is 84 points
ORB_SLAM3复现——上篇