闲来无聊想看看数组各个遍历的方法性能如何
不跑不知道一跑吓一跳
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.491ms
for循环
遍历时长: 0.249ms
for-of循环
遍历时长: 0.268ms
map遍历比for循环慢我也忍了。为啥es6定义的for-of循环比for循环还慢。
让我很费解
温温酱
慕雪6442864
杨魅力
相关分类