2 categories::Collections>Ordered
3 summary:: Array that stores duplicated values more efficiently
6 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.
8 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.
10 The benefits of using SparseArray typically arise when creating collections containing many millions of slots.
15 Create a new SparseArray of the specified strong::size::, with each slot's value being strong::default::.
17 g = SparseArray.newClear(20, 3);
21 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.
23 The default value, i.e. the value that all slots should take at first.
26 Create a new SparseArray holding the same data as strong::array::.
28 a = [4, 7, 4, 4, 4, 4, 4, 4, 9, 9, 8];
29 g = SparseArray.reduceArray(a, 4);
33 Any link::Classes/ArrayedCollection::.
35 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.
42 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).
44 g = SparseArray.newClear(10, 3);
47 g[1] = \hello; // Common compact notation
51 Retrieve the value at index.
53 g = SparseArray.newClear(20, 3);
60 Convert to an ordinary link::Classes/Array::.
62 g = SparseArray.newClear(20, 3);
69 Here we compare speed of Array vs SparseArray.
72 // Let's create a standard array, big but with only a couple of unusual values hidden in there
75 a = {10}.dup(1000000);
80 // Now a SparseArray made out of exactly the same data
83 b = SparseArray.newClear(a.size, 10);
89 // Alternatively you could make the SparseArray out of the existing array,
90 // although this is typically not as efficient as starting from scratch
91 // since the Array needs to be scanned directly.
94 b = SparseArray.reduceArray(a, 10);
99 {1000.do{ a[a.size.rand] == 60.rand }}.bench
100 {1000.do{ b[b.size.rand] == 60.rand }}.bench
102 {1000.do{ a[a.size.rand] = 60.rand }}.bench
103 {1000.do{ b[b.size.rand] = 60.rand }}.bench