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

最终耗时结果图

相关推荐
wjs202438 分钟前
XSLT 实例:掌握 XML 转换的艺术
开发语言
萧鼎42 分钟前
Python第三方库选择与使用陷阱避免
开发语言·python
安冬的码畜日常44 分钟前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
一颗星星辰1 小时前
C语言 | 第十章 | 函数 作用域
c语言·开发语言
lxp1997411 小时前
php函数积累
开发语言·php
太阳花ˉ1 小时前
html+css+js实现step进度条效果
javascript·css·html
科技资讯早知道1 小时前
java计算机毕设课设—坦克大战游戏
java·开发语言·游戏·毕业设计·课程设计·毕设
白拾1 小时前
使用Conda管理python环境的指南
开发语言·python·conda
从0至11 小时前
力扣刷题 | 两数之和
c语言·开发语言