Skip to content

Reduce List resize allocations in PopulateItemGroups hot path - #7083

Merged
donnie-msft merged 1 commit into
NuGet:devfrom
nareshjo:PopulateItemGroups-reduceListResize
Jan 28, 2026
Merged

donnie-msft merged 1 commit into
NuGet:devfrom
nareshjo:PopulateItemGroups-reduceListResize

Conversation

@nareshjo

Copy link
Copy Markdown
Contributor

This pull request was generated by the VS Perf Rel AI Agent. Please review this AI-generated PR with extra care! For more information, visit our wiki. Please share feedback with TIP Insights

  • Issue: ContentItemCollection.PopulateItemGroups() adds items to a List<ContentItemGroup> that starts with default capacity (0). As items are added, the list repeatedly resizes its internal array (0→4→8→16...), allocating new ContentItemGroup[] arrays on each resize.

This matches the allocation stack flow showing PopulateItemGroups → List<>.Add → List<>.EnsureCapacity → List<>.set_Capacity → TypeAllocated!ContentItemGroup[]

nuget.commands.dll!NuGet.Commands.LockFileUtils.GetLockFileItems
nuget.packaging.dll!NuGet.ContentModel.ContentItemCollection.FindBestItemGroup
nuget.packaging.dll!NuGet.ContentModel.ContentItemCollection.PopulateItemGroups
mscorlib.dll!System.Collections.Generic.List`[System.__Canon].Add
mscorlib.dll!System.Collections.Generic.List`[System.__Canon].EnsureCapacity
mscorlib.dll!System.Collections.Generic.List`[System.__Canon].set_Capacity
TypeAllocated!NuGet.ContentModel.ContentItemGroup[]
  • Issue type: Avoid repeated array resize allocations in hot path

  • Proposed fix: Pre-size the list capacity before adding items.
    Before the foreach loop that adds ContentItemGroup items, set list.Capacity to accommodate all incoming items. This eliminates resize allocations since the exact count is known from groupAssets.Count.
    The fix uses a pattern match (is List<T>) to safely access Capacity, falling back gracefully for other IList implementations without affecting functional behavior.

Best practices wiki
See related failure in PRISM
ADO work item

@nareshjo
nareshjo requested a review from a team as a code owner January 26, 2026 23:04
@nareshjo
nareshjo requested review from jebriede and zivkan January 26, 2026 23:04
@dotnet-policy-service dotnet-policy-service Bot added the Community PRs created by someone not in the NuGet team label Jan 26, 2026
@donnie-msft donnie-msft self-assigned this Jan 27, 2026
@donnie-msft
donnie-msft merged commit 5b05c1e into NuGet:dev Jan 28, 2026
16 checks passed
@nareshjo
nareshjo deleted the PopulateItemGroups-reduceListResize branch January 28, 2026 20:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Community PRs created by someone not in the NuGet team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants