Skip to content

Add analyzer for StringBuilder[int] indexer #64545

Closed as not planned
Closed as not planned

Description

@danmoseley

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.

Activity

  1. ghost added
    untriagedNew issue has not been triaged by the area owner
    on Jan 31, 2022
  2. danmoseley commented on Jan 31, 2022

    @danmoseley
    ContributorAuthor

    Analyzer needs to detect both set and get

  3. removed
    untriagedNew issue has not been triaged by the area owner
    on Jul 15, 2022
  4. added this to the Future milestone on Jul 15, 2022
  5. added
    api-suggestionEarly API idea and discussion, it is NOT ready for implementation
    on Nov 9, 2022
  6. modified the milestones: Future, 8.0.0 on Nov 11, 2022
  7. modified the milestones: 8.0.0, Future on Jul 24, 2023
  8. tannergooding commented on Jul 11, 2026

    @tannergooding
    Member

    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

  9. locked and limited conversation to collaborators on Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimecode-analyzerMarks an issue that suggests a Roslyn analyzer

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions