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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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)
Copy link
Member

Choose a reason for hiding this comment

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

Is this branch used in practice? Should we add a Debug.Assert or something that it not become hot again?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I see one path where this would be used. There's one path that passes a ImmutableValuedElementCollectionConverter to the constructor which would hit the "else" path. I can check on how much that happens.

{
if (filter(property))
{
result.Add(selector(property));
}
}

return result;
return result;
}
}
}
}
}