Most efficient way to create a zero filled JavaScript array?

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

    As of ECMAScript2016, there is one clear choice for large arrays.

    Since this answer still shows up near the top on google searches, here's an answer for 2017.

    Here's a current jsbench with a few dozen popular methods, including many proposed up to now on this question. If you find a better method please add, fork and share.

    I want to note that there is no true most efficient way to create an arbitrary length zero filled array. You can optimize for speed, or for clarity and maintainability - either can be considered the more efficient choice depending on the needs of the project.

    When optimizing for speed, you want to: create the array using literal syntax; set the length, initialize iterating variable, and iterate through the array using a while loop. Here's an example.

    const arr = [];
    arr.length = 120000;
    let i = 0;
    while (i < 120000) {
      arr[i] = 0;
      i++;
    }

    Another possible implementation would be:

    (arr = []).length = n;
    let i = 0;
    while (i < n) {
        arr[i] = 0;
        i++;
    }
    

    But I strongly discourage using this second implantation in practice as it's less clear and doesn't allow you to maintain block scoping on your array variable.

    These are significantly faster than filling with a for loop, and about 90% faster than the standard method of

    const arr = Array(n).fill(0);
    

    But this fill method is still the most efficient choice for smaller arrays due to it's clarity, conciseness and maintainability. The performance difference likely won't kill you unless you're making a lot of arrays with lengths on the order of thousands or more.

    A few other important notes. Most style guides recommend you no longer use varwithout a very special reason when using ES6 or later. Use const for variables that won't be redefined and let for variables that will. The MDN and Airbnb's Style Guide are great places to go for more information on best practices. The questions wasn't about syntax, but it's important that people new to JS know about these new standards when searching through these reams of old and new answers.

提交回复
热议问题