Debian Codegraph @

docs/implementation.rst

raw
1 Implementation Details
2 ======================
3
4 The :doc:`Sorted Containers<index>` internal implementation is based on a
5 couple observations. The first is that Python's `list` is fast, *really
6 fast*. Lists have great characteristics for memory management and random
7 access. The second is that `bisect.insort` is fast. This is somewhat
8 counter-intuitive since it involves shifting a series of items in a list. But
9 modern processors do this really well. A lot of time has been spent optimizing
10 mem-copy/mem-move-like operations both in hardware and software.
11
12 But using only one list and `bisect.insort` would produce sluggish behavior for
13 lengths exceeding ten thousand. So the implementation of :doc:`sortedlist` uses
14 a list of lists to store elements. In this way, inserting or deleting is most
15 often performed on a short list. Only rarely does a new list need to be added
16 or deleted.
17
18 :doc:`sortedlist` maintains three internal variables: `_lists`, `_maxes`, and
19 `_index`. The first is simply the list of lists, each member is a sorted
20 sublist of elements. The second contains the maximum element in each of the
21 sublists. This is used for fast binary-search. The last maintains a tree of
22 pair-wise sums of the lengths of the lists.
23
24 Lists are kept balanced using the load factor. If a sublist's length exceeds
25 double the load then it is split in two. Likewise at half the load it is
26 combined with its neighbor. By default this factor is 1,000 which seems to work
27 well for lengths up to ten million. Lengths above that are recommended a load
28 factor that is the square root to cube root of the average length. (Although
29 you will probably exhaust the memory of your machine before that point.)
30 Experimentation is also recommended. A :doc:`load factor performance
31 comparison<performance-load>` is also provided. For more in-depth analysis,
32 read :doc:`performance-scale` which benchmarks :doc:`Sorted Containers<index>`
33 with ten billion elements.
34
35 Finding an element is a two step process. First the `_maxes` list, also known
36 as the "maxes" index, is bisected which yields the position of a sorted
37 sublist. Then that sublist is bisected for the location of the element.
38
39 Compared to tree-based implementations, using lists of lists has a few
40 advantages based on memory usage.
41
42 1. Most insertion/deletion doesn't require allocating or freeing memory. This
43 can be a big win as it takes a lot of strain off the garbage collector and
44 memory system.
45 2. Pointers to elements are packed densely. A traditional tree-based
46 implementation would require two pointers (left/right) to child nodes. Lists
47 have no such overhead. This benefits the hardware's memory architecture and
48 more efficiently utilizies caches.
49 3. The memory overhead per item is effectively a pointer to the item. Binary
50 tree implementations must add at least two more pointers per item.
51 4. Iteration is extremely fast as sequentially indexing lists is a strength of
52 modern processors.
53
54 Traditional tree-based designs have better big-O notation but that ignores the
55 realities of today's software and hardware. For a more in-depth analysis, read
56 :doc:`Performance at Scale<performance-scale>`.
57
58 Indexing uses the `_index` list which operates as a tree of pair-wise sums of
59 the lengths of the lists. The tree is maintained as a dense binary tree. It's
60 easiest to explain with an example. Suppose `_lists` contains sublists with
61 these lengths (in this example, we assume the load factor is 4)::
62
63 list(map(len, _lists)) -> [3, 5, 4, 5, 6]
64
65 Given these lengths, the first row in the index is the pair-wise sums::
66
67 [8, 9, 6, 0]
68
69 We pad the first row with zeros to make its length a power of 2. The next rows
70 of sums work similarly::
71
72 [17, 6]
73 [23]
74
75 Then all the rows are concatenated in reverse order so that the index is
76 finally::
77
78 [23, 17, 6, 8, 9, 6, 0, 3, 5, 4, 5, 6]
79
80 With this list, we can efficiently compute the index of an item in a sublist
81 and, vice-versa, find an item given an index. Details of the algorithms to do
82 so are contained in the docstring for `SortedList._loc` and `SortedList._pos`.
83
84 For example, indexing requires traversing the tree to a leaf node. Each node
85 has two children which are easily computable. Given an index, `pos`, the
86 left-child is at ``pos * 2 + 1`` and the right-child is at ``pos * 2 + 2``.
87
88 When the index is less than the left-child, traversal moves to the left
89 sub-tree. Otherwise, the index is decremented by the left-child and traversal
90 moves to the right sub-tree.
91
92 At a leaf node, the indexing pair is computed from the relative position of the
93 node as compared with the offset and the remaining index.
94
95 For example, given the following index::
96
97 _index = 14 5 9 3 2 4 5
98 _offset = 3
99
100 Tree:
101
102 14
103 5 9
104 3 2 4 5
105
106 Indexing position 8 involves iterating like so:
107
108 1. Starting at the root, position 0, 8 is compared with the left-child node (5)
109 which it is greater than. When greater, the index is decremented and the
110 position is updated to the right child node.
111 2. At node 9 with index 3, we again compare the index to the left-child node
112 with value 4. Because the index is the less than the left-child node, we
113 simply traverse to the left.
114 3. At node 4 with index 3, we recognize that we are at a leaf node and stop
115 iterating.
116 4. To compute the sublist index, we subtract the offset from the index of the
117 leaf node: ``5 - 3 = 2``. To compute the index in the sublist, we simply use
118 the index remaining from iteration. In this case, 3.
119
120 The final index pair from our example is (2, 3) which corresponds to index 8 in
121 the sorted list.
122
123 Maintaining the position index in this way has several advantages:
124
125 * It's easy to traverse to children/parent. The children of a position in the
126 `_index` are at ``(pos * 2) + 1`` and ``(pos * 2) + 2``. The parent is at
127 ``(pos - 1) // 2``. We can even identify left/right-children easily. Each
128 left-child is at an odd index and each right-child is at an even index.
129
130 * It's not built unless needed. If no indexing occurs, the memory and time
131 accounting for position is skipped.
132
133 * It's fast to build. Calculating sums pair-wise and concatenating lists can
134 all be done within C-routines in the Python interpreter.
135
136 * It's space efficient. The whole index is no more than twice the size of the
137 length of the `_lists` and contains only integers.
138
139 * It's easy to update. Adding or removing an item involves incrementing or
140 decrementing only ``log2(len(_index))`` items in the index. The only caveat
141 to this is when a new sublist is created/deleted. In those scenarios the
142 entire index is deleted and not rebuilt until needed.
143
144 The construction and maintenance of the positional index is unusual compared
145 to other traditional designs. Whether the design is novel, I (Grant Jenks) do
146 not know. Until shown otherwise, I would like to refer to it as the "Jenks"
147 index.
148
149 Each sorted container has a function named `_check` for verifying
150 consistency. This function details the data-type invariants.