for循環和forEach的速度問題

for循環是比較古老的循環方式,不少人對他的寫法已經覺得厭煩,隨着js的發展越來越多的遍歷方式逐一誕生:
forEach, map, filter,every,some,for of等等,簡潔的語法讓人賞心悅目。

forEach代碼實現:

	if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisArg */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisArg, t[i], i, t);
    }
  };
}

看看代碼就知道了,forEach的內部實現方式也是通過for循環,加上一連串的判斷怎麼想想都不會覺得比單純的for循環來的快吧!?
首先call調用比直接運行func的成本高, in檢測指定的屬性是否在指定的對象或其原型鏈中,成本也可想而知,forEach自然沒有比常規for循環快的道理。
再者forEach是整個數組遍歷,在針對某個元素操作時候,for循環的break可以提高運行效率。

const names = ['lilei', 'hanmei', 'dave']
for (let i = 0; i < names.length; i++) {
	if (names[i] === 'hanmei') {
		console.log('對hanmei進行操作')
		break
	}
}
names.forEach(name => {
	if(name === 'hanmei') {
		console.log('對hanmei進行操作')
	}
})

同理map的實現方式也類似。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章