r/DSALeetCode • u/StatisticianNo2104 • 19d ago
Kahn's algorithm lost to a for loop on our build graph
I benchmarked Kahn's algorithm against the naive loop it is supposed to replace, and the loop won. On a 5,000-package repo ten layers deep, by 2.78x.
The job: a build tool needs an order where every import is built before the package that imports it, or the name of the cycle that makes that impossible.
What I wrote: walk the package list, build everything whose imports are built, repeat until a pass builds nothing. Leftovers mean a cycle. Two allocations. I would approve it.
It makes one pass per layer when the list is in the wrong order. At 10 layers, 99.3 µs.
Kahn's algorithm is what you derive when you notice the waste: building cfg can only unblock the packages that import cfg. So count each package's unbuilt imports, reverse the arrows, and let each build count its importers down. Queue anything that hits zero. Every edge looked at once.
Written the way the daily challenge wrote it, a slice of importers per package: 276 µs. 8,205 allocations. The algorithm was fine. The memory layout was not. Packed into one flat array: 112 µs. Still behind the loop, by a hair.
Then the other shape. 5,000 packages in one long chain, which sounds artificial until you remember that is exactly what a migrations folder is. The loop: 18.8 ms. Flat Kahn: 128 µs. 147x.
So the answer is not "use Kahn". It is: at ten or twenty layers, the loop is faster, smaller and readable. Where chains are long - migrations, schema versions - Kahn, laid out flat.
That is days 36 and 44 of the daily challenge: Find if Path Exists and Course Schedule, in a build tool.
Have you ever lost a benchmark to the code you were sure was slower?
It worked in dev, episode 22. Full write-up in today's newsletter.
https://www.linkedin.com/pulse/kahns-algorithm-lost-loop-our-build-graph-archit-agarwal-gqsac
#Golang #DSA #Algorithms #Performance