diff --git a/compiler/rustc_type_ir/src/search_graph/mod.rs b/compiler/rustc_type_ir/src/search_graph/mod.rs index 228b6c34b06ed..0a6e351dcdf8f 100644 --- a/compiler/rustc_type_ir/src/search_graph/mod.rs +++ b/compiler/rustc_type_ir/src/search_graph/mod.rs @@ -531,12 +531,25 @@ impl NestedGoals { /// to all nested goals of that nested goal are also inductive. Otherwise the paths are /// the same as for the child. fn extend_from_child(&mut self, step_kind: PathKind, nested_goals: &NestedGoals) { - // Each nested goal is updated independently, and `insert` only unions paths for that - // goal, so traversal order cannot affect the result. - #[allow(rustc::potential_query_instability)] - for (input, paths_to_nested) in nested_goals.iter() { - let paths_to_nested = paths_to_nested.extend_with(step_kind); - self.insert(input, paths_to_nested); + if nested_goals.is_empty() { + return; + } + + // Each nested goal is updated independently, so traversal order cannot + // affect the result. + #[expect(rustc::potential_query_instability)] + if self.is_empty() { + // Manually avoid HashMap lookups for every input if there aren't + // any preexisting entries. + self.nested_goals.clone_from(&nested_goals.nested_goals); + for paths_to_nested in self.nested_goals.values_mut() { + *paths_to_nested = paths_to_nested.extend_with(step_kind); + } + } else { + for (input, paths_to_nested) in nested_goals.iter() { + let paths_to_nested = paths_to_nested.extend_with(step_kind); + self.insert(input, paths_to_nested); + } } }