当前位置:网站首页>js优化双层for循环的方法
js优化双层for循环的方法
2022-07-19 05:52:00 【铁锤妹妹@】
最近在项目中遇到一个需求,需要将两个数据表的数据进行比对,这涉及到了两层for循环的嵌套。数据少的时候还好,一旦数据多就是成倍的循环次数,性能不好,尝试优化一下。
假如两次循环都是1000个元素,那么循环次数是:1000*1000
之前的双层for循环写法:
const withdrawCell = reactive<RenderCell[]>([{
label: '姓名', key: 'realname', type: 'field', col: {
xs: 24, sm: 24, md: 24 }, val: ''
}, {
label: '会员号', key: 'username', type: 'field', col: {
xs: 24, sm: 24, md: 24 }, val: ''
}, {
label: '提现方式', key: 'money_type', type: 'filterDic', dictionary: 'money_withdraw_type', col: {
xs: 24, sm: 24, md: 24 }, val: ''
}, {
label: '账号', key: 'account', type: 'field', col: {
xs: 24, sm: 24, md: 24 }, val: ''
}, {
label: '总金额', key: 'total_amount', type: 'field', col: {
xs: 24, sm: 24, md: 24 }, val: ''
}, {
label: '手续费', key: 'fee', type: 'field', col: {
xs: 24, sm: 24, md: 24 }, val: ''
}
])
for (let i = 0; i < withdrawCell.length; i++) {
for (const j in props.rowInfo) {
// props.rowInfo是一个对象,key键值对的形式
if (withdrawCell[i].key === j) {
switch (withdrawCell[i].type) {
case 'field':
withdrawCell[i].val = props.rowInfo[j]
break
case 'filterDic':
withdrawCell[i].val = filterDic(props.rowInfo[j], useDictionary.originDictionary[withdrawCell[i].dictionary])
break
}
}
}
}
优化后写法
相当于一个for循环就能搞定先判断另一个循环对象里有没有对应的字段,没有就跳出,执行下一个循环
优化之后的循环次数:1000
for (let i = 0; i < withdrawCell.length; i++) {
const item = withdrawCell[i]
//先判断另一个循环对象里有没有对应的字段,没有就跳出,执行下一个循环
if (!props.rowInfo[item.key]) {
continue
}
switch (item.type) {
case 'field':
item.val = props.rowInfo[item.key]
break
case 'filterDic':
item.val = filterDic(props.rowInfo[item.key], useDictionary.originDictionary[item.dictionary])
break
}
}
边栏推荐
猜你喜欢
Design of a simple frequency meter based on FPGA
How can 3dslicer extension modules be added to external expansion packages?
ORC索引的位置信息
MySQL InnoDB engine (4)
FPGA key deblocking - Comparison of two key deblocking forms
Using OpenCV to connect cameras in 3dslicer
C4 学习资料(未完待续)
Impala元数据简介
用float特性填满整个正方形
Verilog grammar basics HDL bits training 02
随机推荐
二叉树的链式存储结构
FPGA uses MATLAB to generate MIF files of four waveforms
动态调整Impala日志级别
管理学重要知识点总结
GC tuning principle of JVM (VIII)
2day
华为机试:单词搜索
playwright教程(二)适合小白
12day
MySQL InnoDB engine (3)
Kubernetes 高可用API Server
13day
Understanding of blocking assignment and non blocking assignment in FPGA
12day
How can 3dslicer extension modules be added to external expansion packages?
仿抖音首页界面
acwing 866. 试除法判定质数
Conception d'un compteur de fréquence simple pour la FPGA
7day
11day