A sparse array is a data structure that acts in exactly the same manner as an Array. However, data is represented differently in memory, in a way that makes it much more efficient to store very large arrays in which many values are the same.
Take for example an array consisting of a million zeroes, with a 1 appended to the end; SparseArray would compress this array by storing zero as a default value, and only explicitly storing the single value that differs, therefore offering a much more economical use of memory.
The benefits of using SparseArray typically arise when creating collections containing many millions of slots.
Create a new SparseArray of the specified size, with each slot's value being default.
size |
Number of slots in the desired array. Note that slots are not explicitly created, so the speed of creation is not related to the array size. |
default |
The default value, i.e. the value that all slots should take at first. |
Create a new SparseArray holding the same data as array.
array |
Any ArrayedCollection. |
default |
The default value, i.e. the value that all slots should take at first. For best memory efficiency, you should supply the most common value found in the collection. |
Put a value at the desired index. This works just like all ArrayedCollection types. Behind the scenes the class will ensure the compact representation (deciding whether to store the value explicitly or implicitly).
Retrieve the value at index.
Convert to an ordinary Array.
Here we compare speed of Array vs SparseArray.