在stringbuider中查看项目的时间复杂度 - C#

时间:2018-01-25 10:31:24

标签: c# time-complexity stringbuilder

我在StringBuilder中保存了一些长文本,我希望获得一些特定项目

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

最后一条指令(char ch = builder[i])的时间复杂度是多少?是不变的

  

O(1)

还是线性的?

  

O(ⅰ)

4 个答案:

答案 0 :(得分:2)

根据Reference SourceStringBuilder类将字符串存储在char数组中。

通过属性getter this[int index]访问此数组会进行一些检查,然后返回数组项:

    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
    }

因此,复杂性是O(1)或持续访问时间。

答案 1 :(得分:1)

这是一个常数,因为你给出了获得元素的确切位置。所以在这种情况下为O(1)。更多细节在这里 What is the complexity of this simple piece of code?

答案 2 :(得分:1)

char ch = builder[i]是O(1)。

因为StringBuilder使用了数组索引。

答案 3 :(得分:1)

查看StringBuilder的实现,它是O(1)因为使用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;