是string.ElementAt()O(1)?

时间:2010-11-30 20:30:44

标签: c# linq string ienumerable

在评论中,it

  

如果源类型实现IList,则该实现用于获取指定索引处的元素。否则,此方法获取指定的元素。

String未实施IList<T>。这是否意味着如果我声明像

这样的话,这将是一个O(n)操作
IEnumerable<char> myString = "stringy";

2 个答案:

答案 0 :(得分:7)

当应用于ElementAt的类型时,

string将是O(N)操作。它没有实现IList<char>,因此ElementAt不会对它进行任何优化,而是通过IEnumerable<char>进行枚举,直到达到指定的索引。

答案 1 :(得分:1)

由于字符串未实现IList,但IEnumerable<char> ElementAt将执行以下代码:

using (IEnumerator<TSource> enumerator = source.GetEnumerator())

和字符串上的GetEnumerator检索CharEnumerator,这是你假设的O(n)。

如果您想要更好的实现,请创建自己的扩展方法

public static class StringExt
{
    public static char ElementAt(this string input, int index)
    {
        if (index < input.Length) return input[index];
        throw new IndexOutOfRangeException();
    }
}

我假设是O(1),但很难说,因为字符串上的索引访问器是在不安全的代码中完成的。