Skip to content

Reduce allocations in EnumsShouldHaveZeroValueAnalyzer #50411

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 4 commits into
base: main
Choose a base branch
from

Conversation

Alex-Sob
Copy link

@Alex-Sob Alex-Sob commented Aug 21, 2025

I would like to suggest PR that is reducing allocations EnumsShouldHaveZeroValueAnalyzer:

  • Currently the analyzer allocates ImmutableArray to store zero value fields of an enum type. It can be removed, in the case when there are multiple zero value fields the analyzer just needs to report an error, it can use a flag for that.

  • GetZeroValueFields method allocates two enumerators with Where and Cast calls, they can be removed.

  • When the analyzer gets zero value field names from analyzer options it allocates string[] with string.Split, ImmutableArray and also a delegate with closure. All those allocations can be removed, particularly string.Split call can be replaced with Span-based splitting.

    There are new MemoryExtensions.Split<T> methods introduced in .NET 9, but they are unavailable for analyzers since they target netstandard2.0. I would probably suggest to provide an internal helper as a simplified version of MemoryExtensions.Split<T> that could be used in analyzers. In this PR, I used it in EnumsShouldHaveZeroValueAnalyzer to reduce allocations.

@Alex-Sob Alex-Sob requested a review from a team as a code owner August 21, 2025 17:12

internal static class SpanExtensions
{
public static SpanSplitEnumerator Split(this ReadOnlySpan<char> source, char separator)
Copy link
Author

Choose a reason for hiding this comment

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

@stephentoub There are new MemoryExtensions.Split<T> methods introduced in .NET 9, but they are unavailable for analyzers since they target netstandard2.0. Do you think it's ok to provide a simplified version to be used for analyzers? For example, it could be used in EnumsShouldHaveZeroValueAnalyzer and considerably reduce allocations. By the way, it seems that Range and Index here are local versions of respective BCL types.

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.

1 participant