@@ -338,11 +338,23 @@ class TestMakeLookup(unittest.TestCase):
338338# /nix/store/tux: {}
339339# }
340340# }
341+subgraphs_cache = {}
341342def make_graph_segment_from_root(root, lookup):
343+ global subgraphs_cache
342344 children = {}
343345 for ref in lookup[root]:
344− debug("Making graph segments on {}".format(ref))
345− children[ref] = make_graph_segment_from_root(ref, lookup)
346+ # make_graph_segment_from_root is a pure function, and will
347+ # always return the same result based on a given input. Thus,
348+ # cache computation.
349+ #
350+ # Python's assignment will use a pointer, preventing memory
351+ # bloat for large graphs.
352+ if ref not in subgraphs_cache:
353+ debug("Subgraph Cache miss on {}".format(ref))
354+ subgraphs_cache[ref] = make_graph_segment_from_root(ref, lookup)
355+ else:
356+ debug("Subgraph Cache hit on {}".format(ref))
357+ children[ref] = subgraphs_cache[ref]
346358 return children
347359
348360class TestMakeGraphSegmentFromRoot(unittest.TestCase):
@@ -393,13 +405,27 @@ class TestMakeGraphSegmentFromRoot(unittest.TestCase):
393405# /nix/store/baz: 4
394406# /nix/store/tux: 6
395407# ]
408+popularity_cache = {}
396409def graph_popularity_contest(full_graph):
410+ global popularity_cache
397411 popularity = defaultdict(int)
398412 for path, subgraph in full_graph.items():
399− debug("Calculating popularity under {}".format(path))
400413 popularity[path] += 1
401− subcontest = graph_popularity_contest(subgraph)
414+ # graph_popularity_contest is a pure function, and will
415+ # always return the same result based on a given input. Thus,
416+ # cache computation.
417+ #
418+ # Python's assignment will use a pointer, preventing memory
419+ # bloat for large graphs.
420+ if path not in popularity_cache:
421+ debug("Popularity Cache miss on {}", path)
422+ popularity_cache[path] = graph_popularity_contest(subgraph)
423+ else:
424+ debug("Popularity Cache hit on {}", path)
425+
426+ subcontest = popularity_cache[path]
402427 for subpath, subpopularity in subcontest.items():
428+ debug("Calculating popularity for {}", subpath)
403429 popularity[subpath] += subpopularity + 1
404430
405431 return popularity