Skip to content
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

[Analyzer] stringBuilder.Append(string.Substring(...)) to stringBuilder.Append(string, ...) #111243

Open
stephentoub opened this issue Jan 9, 2025 · 3 comments
Labels
api-ready-for-review API is ready for review, it is NOT ready for implementation area-System.Runtime code-analyzer Marks an issue that suggests a Roslyn analyzer code-fixer Marks an issue that suggests a Roslyn code fixer untriaged New issue has not been triaged by the area owner

Comments

@stephentoub
Copy link
Member

This pattern shows up reasonably frequently and ends up allocating an additional string:
https://grep.app/search?q=%5C.Append%5C%28%5Cw%2A%5C.Substring&regexp=true&filter[lang][0]=C%23

We should have an analyzer that flags use like:

stringBuilder.Append(string.Substring(offset));
stringBuilder.Append(string.Substring(offset, length));

and a fixer that transforms it into:

stringBuilder.Append(string, offset, string.Length - offset);
stringBuilder.Append(string, offset, length);
@stephentoub stephentoub added api-ready-for-review API is ready for review, it is NOT ready for implementation area-System.Runtime code-analyzer Marks an issue that suggests a Roslyn analyzer code-fixer Marks an issue that suggests a Roslyn code fixer labels Jan 9, 2025
@dotnet-policy-service dotnet-policy-service bot added the untriaged New issue has not been triaged by the area owner label Jan 9, 2025
Copy link
Contributor

Tagging subscribers to this area: @dotnet/area-system-runtime
See info in area-owners.md if you want to be subscribed.

@jilles-sg
Copy link

Rule CA1846 will propose changing Substring to AsSpan which likewise eliminates the allocation. Do we need another analyzer for this case?

@stephentoub
Copy link
Member Author

stephentoub commented Jan 9, 2025

AsSpan won't work / be flagged in a library that targets netstandard, whereas the Append overload that accepts offset and length is available everywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api-ready-for-review API is ready for review, it is NOT ready for implementation area-System.Runtime code-analyzer Marks an issue that suggests a Roslyn analyzer code-fixer Marks an issue that suggests a Roslyn code fixer untriaged New issue has not been triaged by the area owner
Projects
None yet
Development

No branches or pull requests

2 participants