闲来无聊想看看数组各个遍历的方法性能如何不跑不知道一跑吓一跳var nativeMap = function (arr, callback) { return arr.map(callback);};var customMap = function (arr, callback) { var ret = []; for (var i = 0; i < arr.length; i++) { ret.push(callback(arr[i], i, arr)); } return ret;};var forMap = function (arr, callback) { var ret = []; for(let elem of arr){ ret.push(callback(elem)) } return ret;};var run = function (name, times, fn, arr, callback) { // var start = (new Date()).getTime(); console.time('遍历时长'); let newArr; for (var i = 0; i < times; i++) { newArr = fn(arr, callback); } console.log(name); console.timeEnd('遍历时长');};var callback = function (item) { return item+'qwe';};let testArr = ['b','c','d','e','f','d','e','f','d','e','f','d','e','f','d','e','f','d','e','f'];let length = testArr.length;run('map遍历', length, nativeMap, testArr, callback);run('for循环', length, customMap, testArr, callback);run('for-of循环', length, forMap, testArr, callback);map遍历遍历时长: 1.491msfor循环遍历时长: 0.249msfor-of循环遍历时长: 0.268msmap遍历比for循环慢我也忍了。为啥es6定义的for-of循环比for循环还慢。让我很费解
添加回答
举报
0/150
提交
取消