29/38
Part 6 of 7 · The worked exampleLearn

Test the edges, then measure both costs

5. Edge cases.

  • The walk up ends when parent.get returns None after the top. So a file sitting directly in / works like any other.
  • A file nested 100,000 folders deep works too, since every walk is a loop.
  • A new file that wasn't in the pairs is a clarifying question. Add it to parent and children with its folder, give it a total of 0, then resize it.

6. Cost, measured. On a random tree of 100,000 nodes, each under a random earlier one, with sizes on its 50,089 leaves, medians of five runs:

Read the topChange one file
Walk the subtree on every read32.57 msO(1)O(1)
Keep totals, walk up on every change44 ns1.78 µs, 12.3 nodes walked on average
Keep totals, on a chain of 100,00043 ns5.76 ms at the bottom

Building took 124.0 ms, once. Keeping totals turns every read into a lookup and every change into O(h)O(h). On a chain, hh is nn, and the change at the bottom costs nearly what a full read costs the other way: walking the chain's 100,000 nodes took 8.38 ms. Say that trade out loud. Then offer the fix for when both are frequent on a deep tree: number the nodes in pre-order, so every subtree is one range of numbers.