Skip to content

Reduce Allocations in ValidateSignature#2586

Merged
eerhardt merged 1 commit into
devfrom
eerhardt/ReduceListAllocations
May 9, 2024
Merged

Reduce Allocations in ValidateSignature#2586
eerhardt merged 1 commit into
devfrom
eerhardt/ReduceListAllocations

Conversation

@eerhardt

@eerhardt eerhardt commented May 6, 2024

Copy link
Copy Markdown
Contributor

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

eerhardt commented May 6, 2024

Copy link
Copy Markdown
Contributor Author

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.

4 participants