Faster way to access the last and the first element of a List<int>
c#
Solution
`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.
Problem
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() ```