Array.from vs Array.prototype.map

前端 未结 4 1027
耶瑟儿~
耶瑟儿~ 2021-02-18 15:27

So what is the difference between this two functions?

They both create new Array object. Only difference I found so far is that Array.from supp

4条回答
  •  一向
    一向 (楼主)
    2021-02-18 15:52

    Array.map seems to be a bit more performant as well:

    var a = () => [{"count": 3},{"count": 4},{"count": 5}].map(item => item.count);
    var b = () => Array.from([{"count": 3},{"count": 4},{"count": 5}], x => x.count);
    
    var iterations = 1000000;
    console.time('Function #1');
    for(var i = 0; i < iterations; i++ ){
        b();
    };
    console.timeEnd('Function #1')
    
    console.time('Function #2');
    for(var i = 0; i < iterations; i++ ){
        a();
    };
    console.timeEnd('Function #2')
    

    Running this code using Chrome (Version 65.0.3325.181) on this page gave me the follow results:

    Function #1: 520.591064453125ms
    Function #2: 33.622802734375ms
    

提交回复
热议问题