Skip to content

Reduce allocations in JsonRuntimeFormat.ReadRuntimeDescription by pre-sizing List - #7086

Merged
nkolev92 merged 1 commit into
NuGet:devfrom
nareshjo:ReadRuntimeDescription-reduceListResize
Feb 3, 2026
Merged

nkolev92 merged 1 commit into
NuGet:devfrom
nareshjo:ReadRuntimeDescription-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: JsonRuntimeFormat.ReadRuntimeDescription() adds items to a List<string> that starts with default capacity (0). As items are added, the list repeatedly resizes its internal array (0→4→8→16...), allocating new String[] arrays on each resize.

This matches the allocation stack flow showing ReadRuntimeDescription → List<>.Add → List<>.EnsureCapacity → List<>.set_Capacity → TypeAllocated!System.String[]

nuget.packaging.dll!NuGet.RuntimeModel.JsonRuntimeFormat.ReadRuntimeGraph
nuget.packaging.dll!NuGet.RuntimeModel.RuntimeGraph..ctor
system.core.dll!System.Linq.Enumerable.ToDictionary
nuget.packaging.dll!NuGet.RuntimeModel.JsonRuntimeFormat.ReadRuntimeDescription
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!System.String[]
  • Issue type: Avoid repeated array resize allocations in hot path

  • Proposed fix: Pre-size the list capacity using the known JArray.Count.
    Change inheritedRuntimes ??= new() to inheritedRuntimes ??= new List<string>(imports.Count).
    This eliminates resize allocations since the exact count is known upfront from the JArray. The ??= pattern ensures the list is only created on first iteration and reuses it for subsequent items.

Best practices wiki
See related failure in PRISM
ADO work item

@nareshjo
nareshjo requested a review from a team as a code owner January 28, 2026 21:46
@dotnet-policy-service dotnet-policy-service Bot added the Community PRs created by someone not in the NuGet team label Jan 28, 2026
@nkolev92
nkolev92 merged commit a893f4a into NuGet:dev Feb 3, 2026
16 checks passed
@nareshjo
nareshjo deleted the ReadRuntimeDescription-reduceListResize branch February 3, 2026 00:38
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.

4 participants