Most efficient way to create a zero filled JavaScript array?

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

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

30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 06:04

    If you need to create many zero filled arrays of different lengths during the execution of your code, the fastest way I've found to achieve this is to create a zero array once, using one of the methods mentioned on this topic, of a length which you know will never be exceeded, and then slice that array as necessary.

    For example (using the function from the chosen answer above to initialize the array), create a zero filled array of length maxLength, as a variable visible to the code that needs zero arrays:

    var zero = newFilledArray(maxLength, 0);
    

    Now slice this array everytime you need a zero filled array of length requiredLength < maxLength:

    zero.slice(0, requiredLength);
    

    I was creating zero filled arrays thousands of times during execution of my code, this speeded up the process tremendously.

提交回复
热议问题