Are Javascript arrays sparse?

后端 未结 7 2102
情书的邮戳
情书的邮戳 2020-11-22 08:12

That is, if I use the current time as an index into the array:

array[Date.getTime()] = value;

will the interpreter instantiate all the elem

相关标签:
7条回答
  • 2020-11-22 08:59

    They can be but they don't always have to be, and they can perform better when they're not.

    Here's a discussion about how to test for index sparseness in an array instance: https://benmccormick.org/2018/06/19/code-golf-sparse-arrays/

    This code golf (fewest characters) winner is:

    let isSparse = a => !!a.reduce(x=>x-1,a.length)
    

    Basically walking the array for indexed entries while decrementing the length value and returning the hardened !! boolean of the falsy/truthy numerical result (if the accumulator is decremented all the way to zero, the index is fully populated and not sparse). Charles Merriam's caveats above should be considered as well and this code doesn't address them, but they apply to hashed string entries which can happen when assigning elements with arr[var]= (something) where var wasn't an integer.

    On reason to care about index sparseness is its effects on performance, which can differ between script engines, there's a great discussion about array creation/.initialization here: What’s the difference between "Array()" and "[]" while declaring a JavaScript array?

    A recent answer to that post has a link to this deep dive into how V8 tries to optimize arrays by tagging them to avoid (re-)testing for characteristics like sparseness: https://v8.dev/blog/elements-kinds. The blog post is from Sept '17 and the material is subject to some change, but the breakdown to implications for day-to-day development is useful and clear.

    0 讨论(0)
提交回复
热议问题