Add analyzer for StringBuilder[int] indexer #64545
Labels
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-System.Runtime
code-analyzer
Marks an issue that suggests a Roslyn analyzer
Milestone
Indexing into a StringBuilder is not O(1) as one might expect, but O(number of chunks). StringBuilders may have few or one chunks (especially if small, or presized appropriately) or many (especially if it had many appends or grew often). Essentially, StringBuilders are intended for appending, and indexing (or removing) are generally to be avoided.
There are warnings about this in the docs
and some discussion here #24395
As mentioned, indexing is not automatically a perf trap, so an analyzer for it may be noisy, but it's likely worthwhile as it can be a significant problem in some cases, and it's not necessarily obvious. An example of a real perf bug caused by that here dotnet/msbuild#1593
If it is a problem, potential fixes might be: use something other than a StringBuilder (eg., a char buffer, a string); presize the StringBuilder appropriately; or avoid indexing into it. There is no real automatic fixer that could be written.
The analyzer implementation should simply look for use of the StringBuilder indexer, and offer an informational note if it is seen, providing some guidance.
The text was updated successfully, but these errors were encountered: