Most efficient way to create a zero filled JavaScript array?

前端 未结 30 1837
花落未央
花落未央 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:19

    The way I usually do it (and is amazing fast) is using Uint8Array. For example, creating a zero filled vector of 1M elements:

      var zeroFilled = [].slice.apply(new Uint8Array(1000000))
    

    I'm a Linux user and always have worked for me, but once a friend using a Mac had some non-zero elements. I thought his machine was malfunctioning, but still here's the safest way we found to fix it:

      var zeroFilled = [].slice.apply(new Uint8Array(new Array(1000000)) 
    

    Edited

    Chrome 25.0.1364.160

    1. Frederik Gottlieb - 6.43
    2. Sam Barnum - 4.83
    3. Eli - 3.68
    4. Joshua 2.91
    5. Mathew Crumley - 2.67
    6. bduran - 2.55
    7. Allen Rice - 2.11
    8. kangax - 0.68
    9. Tj. Crowder - 0.67
    10. zertosh - ERROR

    Firefox 20.0

    1. Allen Rice - 1.85
    2. Joshua - 1.82
    3. Mathew Crumley - 1.79
    4. bduran - 1.37
    5. Frederik Gottlieb - 0.67
    6. Sam Barnum - 0.63
    7. Eli - 0.59
    8. kagax - 0.13
    9. Tj. Crowder - 0.13
    10. zertosh - ERROR

    Missing the most important test (at least for me): the Node.js one. I suspect it close to Chrome benchmark.

提交回复
热议问题