Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster way to access the last and the first element of a List<int>

Tags:

c#

The language I use is C#.

Let

List<int> numbers = new List<int>();

be a list of integers, that we want to use them to do some calculations. Is it faster to access the first element of the list as

numbers[0]

or as

numbers.First()

Also, if we want to access the last element of the list it is faster to access it as

numbers[numbers.Count-1]

or as

numbers.Last()
like image 470
Christos Avatar asked Dec 02 '13 14:12

Christos


2 Answers

IEnumerable<T> extensions check type of source when you do First() or Last(). If source is IList<T> then indexing is used:

IList<TSource> list = source as IList<TSource>;
if (list != null)
{
    if (list.Count > 0)
    {
        return list[0];
    }
}

So, enumerator will not be created and performance will be almost same. But simple indexing will be of course faster.

like image 53
Sergey Berezovskiy Avatar answered Sep 21 '22 20:09

Sergey Berezovskiy


The index-based accesses (numbers[0] and numbers[numbers.Count - 1], respectively) are probably faster by a very minimal degree, as First() and Last() require the additional method calls of the extension methods First() and Last() before accessing the list items (based on their index, again).

like image 30
O. R. Mapper Avatar answered Sep 20 '22 20:09

O. R. Mapper