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

最终耗时结果图

相关推荐
chushiyunen几秒前
python中的内置属性 todo
开发语言·javascript·python
麦麦鸡腿堡4 分钟前
JavaWeb_请求参数,设置响应数据,分层解耦
java·开发语言·前端
soso196825 分钟前
JavaScript性能调优实战案例
javascript
2301_8194143027 分钟前
C++与区块链智能合约
开发语言·c++·算法
不想看见40434 分钟前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
炸膛坦客37 分钟前
单片机/C/C++八股:(十五)内存对齐、结构体内存对齐
c语言·开发语言·单片机
娇娇yyyyyy1 小时前
QT编程(13): Qt 事件机制eventfilter
开发语言·qt
bcbobo21cn1 小时前
C# byte类型和byte数组的使用
开发语言·c#·字节数组·byte类型
计算机安禾1 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
阿贵---1 小时前
C++构建缓存加速
开发语言·c++·算法