Skip to content

Conversation

Erarndt
Copy link
Contributor

@Erarndt Erarndt commented Sep 23, 2025

Fixes #

Context

There is a meaningful amount of allocations coming from resizing a List<T> in CopyOnReadEnumerable.GetEnumerator()

image

Total allocations in this path are ~68MB for OrchardCore. We won't eliminate them entirely, but this will reduce them.

Changes Made

Testing

Notes

@Copilot Copilot AI review requested due to automatic review settings September 23, 2025 23:48
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR optimizes the CopyOnReadEnumerable.GetEnumerator() method by checking for ICollection<T> to get the collection count before initializing a List<T>. This reduces memory allocations by avoiding list resizing during enumeration.

  • Adds ICollection<T> check to obtain count before IReadOnlyCollection<T> check
  • Uses collection count for initial List<T> capacity to prevent dynamic resizing
  • Targets ~68MB allocation reduction in OrchardCore scenarios

Comment on lines +75 to +78
else if (_backingEnumerable is ICollection<TSource> collection)
{
list = new List<TResult>(collection.Count);
}
Copy link
Preview

Copilot AI Sep 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ICollection<T> check should be placed before the IReadOnlyCollection<T> check since ICollection<T> is more specific and commonly implemented. Consider reordering these conditions to check ICollection<T> first for better performance in common scenarios.

Copilot uses AI. Check for mistakes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant