【宇润日常疯测-004】JS 遍历数组如何快!快!快!

首先,我就是一后端全栈,对前端也只是会用罢了。闲的无聊来测测,不深究,只看表面,不喜勿喷!

遍历数组在写 JS 代码时候一定是经常用的,那么怎么遍历能达到最高效率呢,很多人一定没有测试过!

测试环境:Chrome 71.0.3578.80 + F12 开发者工具

此次测试,我使用 6 种方法进行测试,它们分别是:2种 for 、forEach、for in、for of以及map。

var list = [];
for(var i = 0; i < 100000; ++i)
{
	list.push(Math.random());
}

function test1(list)
{
	var s = 0;
	for(var i = 0; i < list.length; ++i)
	{
		s += i;
	}
	return s;
}

function test2(list)
{
	var s = 0;
	var count = list.length;
	for(var i = 0; i < count; ++i)
	{
		s += i;
	}
	return s;
}

function test3(list)
{
	var s = 0;
	list.forEach(function(value){
		s += value;
	});
	return s;
}

function test4(list)
{
	var s = 0;
	for(var i in list)
	{
		s += list[i];
	}
	return s;
}

function test5(list)
{
	var s = 0;
	list.map(function(value){
		s += value;
	});
	return s;
}

function test6(list)
{
	var s = 0;
	for(let value of list) {  
	   s += value;
	};
	return s;
}

console.time('list.length')
test1(list);
console.timeEnd('list.length');

console.time('count')
test2(list);
console.timeEnd('count');

console.time('forEach')
test3(list);
console.timeEnd('forEach');

console.time('for in')
test4(list);
console.timeEnd('for in');

console.time('map')
test5(list);
console.timeEnd('map');

console.time('for of')
test6(list);
console.timeEnd('for of');

测试结果

list.length: 2.52294921875ms

count: 2.19775390625ms

forEach: 3.802978515625ms

for in: 23.849853515625ms

map: 33.470947265625ms

for of: 7.194091796875ms

结论

以下结论仅供参考,仅在单纯遍历数组时有效,如果有其它需求可能不适用,请自行取舍。

性能最佳:定义一个变量,把list.count存起来,然后 < 这个变量作为条件来循环。

当然,直接for循环将list.count作为条件来循环,性能也不比上面的差多少,偷懒也是可以用的。

forEach、for of 性能也还行。

for in 和 map 能不用尽量不用,性能太差了!

  • 发表评论
当前用户:
  • 评论列表
  • 最新文章
  • 最新评论