开原网站网站建设,太原制作网站的工作室,seo公司上海,洛浦县网站建设最近实习遇到一个问题#xff0c;需要对折线图的数据进行范围限制#xff0c;比如将超过100的设置为100#xff0c;低于0的设置为0#xff1b; 原来的代码是创建一个数组#xff0c;然后遍历原数组#xff0c;超过的push100#xff0c;低于0的push0#xff0c;在中间的…最近实习遇到一个问题需要对折线图的数据进行范围限制比如将超过100的设置为100低于0的设置为0 原来的代码是创建一个数组然后遍历原数组超过的push100低于0的push0在中间的按原值传但我觉得这会导致性能问题一旦传入多个值会严重影响性能别问我为什么知道的 这时候我想起mapmap的性能是很差的但是不需要创建数组的情况下是否会比forEach新数组push更优呢直接开始实践~
let arr []
for (let i 0; i 5000000; i) {arr[i] Math.random() * 100 50
}
console.log(首先是map)
let mapstart;
let mapend;
mapstart new Date().getTime()
let arr1 arr.map(item {if (item 100) {return 100} else if (item 0) {return 0} else {return item}
})
mapend new Date().getTime()
console.log(mapend - mapstart)
console.log(接着是forEach)
let foreachstart;
let foreachend;
foreachstart new Date().getTime()
let arr2 []
arr.forEach(item {if (item 100) {arr2.push(100)} else if (item 0) {arr2.push(0)} else {arr2.push(item)}
})
foreachend new Date().getTime()
console.log(foreachend - foreachstart)
console.log(接着是for)
let forstart;
let forend;
forstart new Date().getTime()
let arr3 []
for (let i 0; i arr.length; i) {if (arr[i] 100) {arr3.push(100)} else if (arr[i] 0) {arr3.push(0)} else {arr3.push(arr[i])}
}
forend new Date().getTime()
console.log(forend - forstart)
console.log(arr1)
console.log(arr2)
console.log(arr3)输出结果 低数据情况下输出时间差不多 500W数据的输出结果。。。 map被完爆了那竟然性能这么不好为什么要用map呢 引用了这个博主的文章 https://www.cnblogs.com/raind/p/8557120.html 他的说法是使用map的算法更加清晰简洁。