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

最终耗时结果图

相关推荐
钢铁男儿42 分钟前
C# 方法(栈帧)
开发语言·c#
忆源3 小时前
【Qt】之音视频编程1:QtAV的背景和安装篇
开发语言·qt·音视频
敲键盘的小夜猫3 小时前
Python核心数据类型全解析:字符串、列表、元组、字典与集合
开发语言·python
李匠20243 小时前
C++GO语言微服务之图片、短信验证码生成及存储
开发语言·c++·微服务·golang
apcipot_rain4 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
油丶酸萝卜别吃4 小时前
OpenLayers 精确经过三个点的曲线绘制
javascript
ShallowLin4 小时前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧4 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
互联网搬砖老肖4 小时前
Web 架构之攻击应急方案
前端·架构
pixle05 小时前
Vue3 Echarts 3D饼图(3D环形图)实现讲解附带源码
前端·3d·echarts