当前位置:网站首页>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
边栏推荐
- Compilation of program
- OV7725 yuv 640*[email protected] 配置文件
- 更新|3DCAT实时云渲染 v2.1.2版本全新发布
- Sequential storage structure, chain storage structure and implementation of stack
- 408 Chapter 2 linear table
- Recommend a qinheng Bluetooth reference blog
- "Deprecated gradle features were used in this build, making it incompatible with gradle 6.0" problem solving
- Error when starting MySQL on Linux
- Oracle使用impdp导入报错:ORA-39001: 参数值无效 ORA-39000: 转储文件说明错误 ORA-39088: 文件名不能包含路径说明
- Kendryte K210 在freertos上的lcd屏幕的使用
猜你喜欢

SQL things

LeetCode 101. 对称二叉树 && 100. 相同的树 && 572. 另一棵树的子树

BiSeNet v1

专访即构科技李凯:音视频的有趣、行业前沿一直吸引着我

Use of LCD screen of kendryte k210 on FreeRTOS

pd.melt() vs reshape2::melt()

这是一张机器&深度学习代码速查表

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

Kendryte K210 在freertos上的lcd屏幕的使用

Imx6 rtl8189ftv migration
随机推荐
Remember those two sentences
[HAOI2015]树上操作
基于Caffe ResNet-50网络实现图片分类(仅推理)的实验复现
7. 依赖注入
What scenarios have rust, which is becoming more and more mature, applied?
超全Mavan标签详解
srec_ Use of common cat parameters
Combined with GHS multi, use Reza E1 simulator to realize the simulation and debugging of Reza rh850 single chip microcomputer
云VR:虚拟现实专业化的下一步
408 Chapter 2 linear table
Why is the index in [mysql] database implemented by b+ tree? Is hash table / red black tree /b tree feasible?
LeetCode 101. 对称二叉树 && 100. 相同的树 && 572. 另一棵树的子树
二叉树的相关操作
11.2-HJ86 求最大连续bit数
Tkinter GUI address book management system
一周活动速递|深入浅出第8期;Meetup成都站报名进行中
乐观锁解析
[NOI2015] 软件包管理器
"Jargon" | what kind of experience is it to efficiently deliver games with Devops?
SQL那些事