Performance comparison of js array traversal

I want to see how each traversal method works in the array.
I don"t know if I don"t know how to run and jump when I"m not running.

var nativeMap = function (arr, callback) {
    return arr.map(callback);
};
var customMap = function (arr, callback) {
    var ret = [];
    for (var i = 0; i < arr.length; iPP) {
        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; iPP) {
        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 traversal is slower than for loop, and I put up with it. Why the for-of loop defined by es6 is slower than the for loop.
puzzles me

Mar.12,2021

upstairs is right, the time is too short, the performance of the latter two is difficult to distinguish. Second, because the time is too short, it may also be because the things done in callback are different, so map seems to be more time-consuming. When you try to improve the performance of something, you usually need extra overhead, and when the performance improvement you get with these costs is not enough to offset the cost, the performance will decline; when the load is raised, the performance improvement will outweigh the overhead. There will be a significant performance improvement. I once sorted and sorted through an array of thousands of elements using the for loop, and the browser just jammed, ate 2 gigabytes of memory, and traversed it in a few seconds after replacing map .


clipboard.png

such a short time is not accurate


it is not accurate to make a comparison in such a short time, and it is only the result of one execution.

Menu