Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1244
花落未央
花落未央 2020-11-22 05:58

What is the most efficient way to create an arbitrary length zero filled array in JavaScript?

30条回答
  •  旧时难觅i
    2020-11-22 06:10

    My fastest function would be:

    function newFilledArray(len, val) {
        var a = [];
        while(len--){
            a.push(val);
        }
        return a;
    }
    
    var st = (new Date()).getTime();
    newFilledArray(1000000, 0)
    console.log((new Date()).getTime() - st); // returned 63, 65, 62 milliseconds
    

    Using the native push and shift to add items to the array is much faster (about 10 times) than declaring the array scope and referencing each item to set it's value.

    fyi: I consistently get faster times with the first loop, which is counting down, when running this in firebug (firefox extension).

    var a = [];
    var len = 1000000;
    var st = (new Date()).getTime();
    while(len){
        a.push(0);
        len -= 1;
    }
    console.log((new Date()).getTime() - st); // returned 863, 894, 875 milliseconds
    st = (new Date()).getTime();
    len = 1000000;
    a = [];
    for(var i = 0; i < len; i++){
        a.push(0);
    }
    console.log((new Date()).getTime() - st); // returned 1155, 1179, 1163 milliseconds
    

    I'm interested to know what T.J. Crowder makes of that ? :-)

提交回复
热议问题