1. 程式人生 > >【宇潤日常瘋測-004】JS 遍歷陣列如何快!快!快!

【宇潤日常瘋測-004】JS 遍歷陣列如何快!快!快!

首先,我就是一後端全棧,對前端也只是會用罷了。閒的無聊來測測,不深究,只看表面,不喜勿噴!

遍歷陣列在寫 JS 程式碼時候一定是經常用的,那麼怎麼遍歷能達到最高效率呢,很多人一定沒有測試過!

測試環境:Chrome 71.0.3578.80 + F12 開發者工具

此次測試,我使用 6 種方法進行測試,它們分別是:2種 forforEachfor infor 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作為條件來迴圈,效能也不比上面的差多少,偷懶也是可以用的。

forEachfor of 效能也還行。

for inmap 能不用盡量不用,效能太差了!