5/35
Part 1 of 7 · Dict of dictsLearn
In Python, a trie of 100,000 words took about 8 times a set's memory
Every node is a whole dict, and the trie pays for that in memory. Here's the measurement:
import random
import sys
import tracemalloc
with open("/usr/share/dict/words") as f:
every = sorted({w for w in f.read().split() if w.isascii() and w.isalpha() and w.islower()})
# 968,341 letters in all
words = random.Random(7).sample(every, 100_000)
tracemalloc.start()
trie = {}
for word in words:
insert(trie, word)
trie_bytes = tracemalloc.get_traced_memory()[0]
tracemalloc.stop()
tracemalloc.start()
word_set = set(words)
set_bytes = tracemalloc.get_traced_memory()[0] + sum(sys.getsizeof(w) for w in words)
tracemalloc.stop()
The word list for every large measurement in this lesson is these 100,000 words, drawn at random from the lowercase words in /usr/share/dict/words, the list that ships with macOS.
sys.getsizeof({"a": {}}) returns a size in bytes. Does that number include the inner dict?
Pick an answer above to see the rest