views:

350

answers:

7

I was thinking about the performance of calling List<T>.Indexof(item). I am not sure if it will be a O(n) performance for a sequential algorithm or O(log(n)) performance for a binary tree??

Thanks!

+2  A: 

Behind the scenes a regular arrayis used, infact the IndexOf method simply calls Array.IndexOf. Since arrays don't sort elements, performance is O(n).

Bob
+17  A: 

Using Reflector for .NET we can see:

public int IndexOf(T item)
{
    return Array.IndexOf<T>(this._items, item, 0, this._size);
}

public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
{
    return EqualityComparer<T>.Default.IndexOf(array, value, startIndex, count);
}

internal virtual int IndexOf(T[] array, T value, int startIndex, int count)
{
    int num = startIndex + count;
    for (int i = startIndex; i < num; i++)
    {
        if (this.Equals(array[i], value))
            return i;
    }
    return -1;
}
abatishchev
Don't ever look at the code when there's detailed documentation. Sometimes the code is just an implementation detail, and there are no guarantees.
Ken Bloom
@Ken Bloom: MSDN articles sometimes are very good, sometime are awful. So if you have a question about implementation of specific method, I think the best way - go and see how does it really implemented.
abatishchev
When the code and comments disagree, both are probably wrong.
Malfist
+16  A: 

It's O(n) according to MSDN.

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

IVlad
Damn, beat me by 50 seconds. +1 :)
Jeff Yates
+5  A: 

List<T> is backed by a flat array, so list.IndexOf(item) is O(n).

JSBangs
+2  A: 

If you need a faster performer, consider HashSet<T>. It's a speed vs. memory tradeoff, but it is worth it if you value the former over the latter.

(It's not exactly the same as a List<T>, it behaves like a single column dictionary, but for instances where you are going to have a unique list, it's one way to do it.)

Anthony Pegram
+3  A: 

List<T>.IndexOf is O(n) which is in fact optimal for an unordered set of n elements.

List<T>.BinarySearch is O(log n) but only works correctly if the List is sorted.

C. Dragon 76
A: 

This is a old question, but I thought this link would be interesting: Experiment: List internals and performance when adding new elements

lasseespeholt