From d4c3e5836c5898f073d577032e527518115a9b48 Mon Sep 17 00:00:00 2001 From: jesse <149186008+BigWorkk@users.noreply.github.com> Date: Sat, 17 Oct 2026 14:09:48 -0500 Subject: [PATCH] Avoid command lookup allocation for absolute paths Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../engine/CommandPathSearch.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 12c494ad8ea..30a0b146d7e 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -97,7 +97,7 @@ internal CommandPathSearch( /// private void ResolveCurrentDirectoryInLookupPaths() { - var indexesToRemove = new SortedDictionary(); + SortedDictionary? indexesToRemove = null; int removalListCount = 0; string fileSystemProviderName = _context.ProviderNames.FileSystem; @@ -199,6 +199,7 @@ private void ResolveCurrentDirectoryInLookupPaths() // The relative path index is less than the explicit path, // so remove the explicit path. + indexesToRemove ??= new SortedDictionary(); indexesToRemove.Add(removalListCount++, existingIndex); _lookupPaths[index] = resolvedDirectory; } @@ -207,6 +208,7 @@ private void ResolveCurrentDirectoryInLookupPaths() // The explicit path index is less than the relative path // index, so remove the relative path. + indexesToRemove ??= new SortedDictionary(); indexesToRemove.Add(removalListCount++, index); } } @@ -222,6 +224,7 @@ private void ResolveCurrentDirectoryInLookupPaths() // The directory couldn't be resolved so remove it from the // lookup paths. + indexesToRemove ??= new SortedDictionary(); indexesToRemove.Add(removalListCount++, index); } } @@ -230,10 +233,13 @@ private void ResolveCurrentDirectoryInLookupPaths() // As each element is removed, elements that follow are moved up to occupy // the emptied index. - for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex) + if (indexesToRemove is not null) { - int indexToRemove = indexesToRemove[removeIndex - 1]; - _lookupPaths.RemoveAt(indexToRemove); + for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex) + { + int indexToRemove = indexesToRemove[removeIndex - 1]; + _lookupPaths.RemoveAt(indexToRemove); + } } }