js进行数据移除性能比较(splice,map)

当使用 splice() 方法处理大量数据时,确实会遇到性能问题,因为它涉及到移动数组中的元素,导致操作的时间复杂度为 O(n)。对于大量数据,频繁的插入和删除可能会导致性能下降。

1、设置数组数据为10000,使用splice移除数组中的所有数据耗时,示例如下:

复制代码
let tempList = [];
for(let i = 0;i<10000;i++){
	let obj = i+1;
	tempList.push(obj),
}
/**使用splice去除元素时间*/
spliceOpt();
function spliceOpt(){
	let startTime = Date.now();
	for(let i = 0;i<10000;i++){
		let index = tempList.indexOf(i+1);
		if(index>-1){
		  tempList.splice(index,1)
		}
	}
	let endTime = Date.now();
	let useTime = endTime - startTime;
	console.log(tempList,useTime,"第一种方法使用时间")
}

2、设置数组数据为10000,使用map移除数组中的所有数据耗时,示例如下:

复制代码
let currentMap = new Map();
for(let i = 0;i<10000;i++){
	let obj = i+1;
	currentMap.set(obj,obj)
}
/**使用Map去除元素时间*/
mapOPt();
function mapOPt(){
	let startTime = Date.now();
	for(let i = 0;i<10000;i++){
		if(currentMap.has(i+1)){
			currentMap.delete(i+1);
		}
	}
	let endTime = Date.now();
	let useTime = endTime - startTime;
	console.log(currentMap,useTime,"第二种方法使用时间")
}

最终耗时结果图

相关推荐
于冬恋几秒前
Web后端开发(请求、响应)
前端
YuTaoShao1 分钟前
Java八股文——集合「List篇」
java·开发语言·list
red润6 分钟前
封装hook,复刻掘金社区,暗黑白天主题切换功能
前端·javascript·vue.js
Fly-ping8 分钟前
【前端】vue3性能优化方案
前端·性能优化
curdcv_po9 分钟前
前端开发必要会的,在线JS混淆加密
前端
天生我材必有用_吴用11 分钟前
深入理解JavaScript设计模式之单例模式
前端
LuckySusu11 分钟前
【HTML篇】DOCTYPE 声明:掌握浏览器渲染模式的关键
前端·html
Darling哒12 分钟前
HTML块拖拽交换
前端
码农之王13 分钟前
(一)TypeScript概述和环境搭建
前端·后端·typescript
葬送的代码人生24 分钟前
React组件化哲学:如何优雅地"变秃也变强"
前端·javascript·react.js