2

I have some long text saved in StringBuilder and I want to get some specific item

StringBuilder builder = new StringBuilder();
//fill builder
int i = someNumber();
char ch = builder[i];

what is the time-complexity of the last instruction (char ch = builder[i])? Is it constant

O(1)

or is it linear?

O(i)

Stastny Jakub
  • 156
  • 1
  • 16

4 Answers4

2

As per Reference Source the StringBuilder class stores strings in a char Array.

Accessing this array via the property getter this[int index] does a few checks and then returns the array item:

    internal char[] m_ChunkChars;                // The characters in this block
    //...more stuff

    [System.Runtime.CompilerServices.IndexerName("Chars")]
    public char this[int index] {
        // 

        get {
            StringBuilder chunk = this;
            for (; ; )
            {
                int indexInBlock = index - chunk.m_ChunkOffset;
                if (indexInBlock >= 0)
                {
                    if (indexInBlock >= chunk.m_ChunkLength)
                        throw new IndexOutOfRangeException();
                    return chunk.m_ChunkChars[indexInBlock];
                }
                chunk = chunk.m_ChunkPrevious;
                if (chunk == null)
                    throw new IndexOutOfRangeException();
            }
        }
        //... more stuff
    }

Thus the complexity is O(1) or constant access time.

Adwaenyth
  • 2,020
  • 12
  • 24
1

It is a constant as you are giving exact location to get the element.So in this case O(1). More details here What is the complexity of this simple piece of code?

JyothiJ
  • 315
  • 1
  • 11
1

char ch = builder[i] is O(1) .

Because StringBuilder used array index.

D-Shih
  • 44,943
  • 6
  • 31
  • 51
1

Looking at the implementation of StringBuilder, it is O(1) because is use char[]

    //
    //
    //  CLASS VARIABLES
    //
    //
    internal char[] m_ChunkChars;                // The characters in this block
    internal StringBuilder m_ChunkPrevious;      // Link to the block logically before this block
    internal int m_ChunkLength;                  // The index in m_ChunkChars that represent the end of the block
    internal int m_ChunkOffset;                  // The logial offset (sum of all characters in previous blocks)
    internal int m_MaxCapacity = 0;
Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28