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()
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With