Skip to content

Conversation

@eerhardt
Copy link
Contributor

@eerhardt eerhardt commented May 6, 2024

When we need to create an enumerable with a single element in it, we are allocating a new List<SecurityKey> { key }. This allocates both the list, and then allocates a 4 element array backing the list (because this syntax is C# sugar for just calling Add on the collection).

Instead, use a collection expression which optimizes the single element case.

There was one method in Saml that had this pattern in it, but was unused. I opted to remove it. Please let me know if it should be preserved for some reason.

Using an internal benchmark with 1,000 iterations, these allocations will be cut in half:

image

When we need to create an enumerable with a single element in it, we are allocating a `new List<SecurityKey> { key }`. This allocates both the list, and then allocates a 4 element array backing the list (because this syntax is C# sugar for just calling Add on the collection).

Instead, use a collection expression which optimizes the single element case.

There was one method in Saml that had this pattern in it, but was unused. I opted to remove it. Please let me know if it should be preserved for some reason.
@eerhardt eerhardt requested a review from a team as a code owner May 6, 2024 21:05
@eerhardt
Copy link
Contributor Author

eerhardt commented May 6, 2024

See dotnet/roslyn#71147 for what Roslyn does in these cases. It generates a <>z__ReadOnlySingleElementList class that is used for the single element case.

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.

5 participants