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,"第二种方法使用时间")
}

最终耗时结果图

相关推荐
磊 子2 分钟前
STL之deque和list以及两者与vector的对比
开发语言·c++·list
凤山老林4 分钟前
DDD(领域驱动设计)在复杂业务系统中的落地指南
java·开发语言·数据库·ddd·领域驱动
Dazer0079 分钟前
Edge 浏览器绕过 HTTPS 证书错误
前端·https·edge
凯瑟琳.奥古斯特15 分钟前
子查询原理与实战案例解析
开发语言·数据库·职场和发展·数据库开发
元让_vincent16 分钟前
Spark 2.0:面向 Web 的 3DGS 可视化与大场景渲染平台详解
前端·3d·spark·渲染·轻量化·3dgs·lod
Eiceblue16 分钟前
Python 操作 Excel:数据分组、分类汇总与取消分组全解
开发语言·python·excel
山上三树18 分钟前
C/C++ 高频报错速查表(开发通用版)
c语言·开发语言·c++
Tian_Hang25 分钟前
Factory Method | 工厂方法
开发语言·c++
KaMeidebaby33 分钟前
卡梅德生物技术快报|酵母双杂交 cDNA 文库构建与蛋白互作筛选流程
服务器·前端·数据库·人工智能·算法
wearegogog12334 分钟前
基于MATLAB实现雷达RCS Swerling模型
开发语言·matlab