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

最终耗时结果图

相关推荐
over69710 分钟前
JavaScript恋爱物语:当代码学会送花,对象字面量也能当红娘!
javascript
tiantian_cool15 分钟前
HarmonyOS 开发环境配置指南 - macOS 版
前端
foundbug99917 分钟前
基于CSMA-CA协议的V2X通信MATLAB仿真
开发语言·网络·matlab
WangMing_X28 分钟前
C#上位机软件:2.5 体验CLR实现多语言混合编程
java·开发语言·c#
jerryinwuhan30 分钟前
pybullet入门到入门_1
开发语言·人工智能·python
写不来代码的草莓熊35 分钟前
vue前端面试题——记录一次面试当中遇到的题(10)
前端·vue.js·面试
tiantian_cool41 分钟前
正确的 .gitignore 配置
前端·github
三小河43 分钟前
封装 classNames:让 Tailwindcss 类名处理更优雅
前端·javascript
豐儀麟阁贵43 分钟前
4.4数组的基本操作
java·开发语言·数据结构·算法
Moniane44 分钟前
XMW技术:颠覆未来的创新引擎
开发语言