(perf) optimize assign-depths

This commit is contained in:
David Michon 2025-02-05 11:33:07 -08:00
parent 4815712a1d
commit e83fb236ee
1 changed files with 17 additions and 15 deletions

View File

@ -3895,28 +3895,30 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o
assignDepths(modules) {
const moduleGraph = this.moduleGraph;
/** @type {Set<Module | number>} */
/** @type {Set<Module>} */
const queue = new Set(modules);
queue.add(1);
// Track these in local variables so that queue only has one data type
let nextDepthAt = queue.size;
let depth = 0;
let i = 0;
for (const module of queue) {
i++;
if (typeof module === "number") {
depth = module;
if (queue.size === i) return;
queue.add(depth + 1);
} else {
moduleGraph.setDepth(module, depth);
for (const { module: refModule } of moduleGraph.getOutgoingConnections(
module
)) {
if (refModule) {
queue.add(refModule);
}
moduleGraph.setDepth(module, depth);
// Some of these results come from cache, which speeds this up
const connections = moduleGraph.getOutgoingConnectionsByModule(module);
// connections will be undefined if there are no outgoing connections
if (connections) {
for (const refModule of connections.keys()) {
if (refModule) queue.add(refModule);
}
}
i++;
// Since this is a breadth-first search, all modules added to the queue
// while at depth N will be depth N+1
if (i >= nextDepthAt) {
depth++;
nextDepthAt = queue.size;
}
}
}