Skip to content

Reduce allocations in PropertyDictionary #11807

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 15, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/Build/Collections/PropertyDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -551,19 +551,38 @@ internal void Enumerate(Action<string, string> keyValueCallback)

internal IEnumerable<TResult> Filter<TResult>(Func<T, bool> filter, Func<T, TResult> selector)
{
List<TResult> result = new();
lock (_properties)
{
foreach (T property in (ICollection<T>)_properties)
// PERF: Prefer using struct enumerators from the concrete types to avoid allocations.
// RetrievableValuedEntryHashSet implements a struct enumerator.
if (_properties is RetrievableValuedEntryHashSet<T> hashSet)
{
if (filter(property))
List<TResult> result = new(hashSet.Count);
foreach (T property in hashSet)
{
result.Add(selector(property));
if (filter(property))
{
result.Add(selector(property));
}
}

return result;
}
}
else
{
ICollection<T> propertiesCollection = _properties;
List<TResult> result = new(propertiesCollection.Count);
foreach (T property in propertiesCollection)
{
if (filter(property))
{
result.Add(selector(property));
}
}

return result;
return result;
}
}
}
}
}