You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add analyzer for StringBuilder[int] indexer #64545
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.
There are likely ways we could improve the issue in StringBuilder itself. Such as reworking the indexers to avoid less repetitive work, relying on the default growth algorithm doubling the previous length, etc.
That all being said this is a relatively low interest/engagement issue and unlikely to be gotten to given the size/scope of the backlog. While it is a potential issue that comes up, its unlikely to see prioritization and/or implementation
Activity
danmoseley commentedon Jan 31, 2022
Analyzer needs to detect both set and get
tannergooding commentedon Jul 11, 2026
There are likely ways we could improve the issue in StringBuilder itself. Such as reworking the indexers to avoid less repetitive work, relying on the default growth algorithm doubling the previous length, etc.
That all being said this is a relatively low interest/engagement issue and unlikely to be gotten to given the size/scope of the backlog. While it is a potential issue that comes up, its unlikely to see prioritization and/or implementation
Simplify StringBuilder indexer to reuse FindChunkForIndex (#130554)
Simplify StringBuilder indexer to reuse FindChunkForIndex (#130554)