Skip to content

Commit ccf3981

Browse files
Use Builder in ImmutableDictionary.SetItems extension (#12402)
### Context Small change to avoid allocating a generated enumerable. Using a `Builder` here is otherwise identical in perf to `SetItems`, as both hit the same paths to allocate a new instance + modified subtree nodes. ~34MB diff below.
1 parent f1c9383 commit ccf3981

1 file changed

Lines changed: 9 additions & 13 deletions

File tree

src/Framework/ImmutableDictionaryExtensions.cs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ internal static class ImmutableDictionaryExtensions
1616
public static readonly ImmutableDictionary<string, string> EmptyMetadata =
1717
ImmutableDictionary<string, string>.Empty.WithComparers(MSBuildNameIgnoreCaseComparer.Default);
1818

19+
#if !TASKHOST
1920
/// <summary>
2021
/// Sets the given items while running a validation function on each key.
2122
/// </summary>
@@ -29,23 +30,18 @@ public static ImmutableDictionary<string, string> SetItems(
2930
IEnumerable<KeyValuePair<string, string>> items,
3031
Action<string> verifyThrowKey)
3132
{
32-
return dictionary.SetItems(ValidateItems(items, verifyThrowKey));
33+
ImmutableDictionary<string, string>.Builder builder = dictionary.ToBuilder();
3334

34-
// PERF: This extra allocation is still faster than enumerating ImmutableDictionary after modification.
35-
static IEnumerable<KeyValuePair<string, string>> ValidateItems(
36-
IEnumerable<KeyValuePair<string, string>> items,
37-
Action<string> verifyThrowKey)
35+
foreach (KeyValuePair<string, string> item in items)
3836
{
39-
foreach (KeyValuePair<string, string> item in items)
40-
{
41-
verifyThrowKey(item.Key);
37+
verifyThrowKey(item.Key);
4238

43-
// Set null as empty string to match behavior with ProjectMetadataInstance.
44-
yield return item.Value == null
45-
? new KeyValuePair<string, string>(item.Key, string.Empty)
46-
: item;
47-
}
39+
// Set null as empty string to match behavior with ProjectMetadataInstance.
40+
builder[item.Key] = item.Value ?? string.Empty;
4841
}
42+
43+
return builder.ToImmutable();
4944
}
45+
#endif
5046
}
5147
}

0 commit comments

Comments
 (0)