A faster way to access the last and first element of the <int> list

I am using C # language.

Let be

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

is a list of integers that we want to use to perform some calculations. Is access to the first element of the list faster as

 numbers[0] 

or

 numbers.First() 

In addition, if we want to access the last element of the list, it will access it faster as

 numbers[numbers.Count-1] 

or

 numbers.Last() 
+6
source share
4 answers

IEnumerable<T> extensions check the source type when executing First() or Last() . If the 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, the enumerator will not be created, and the performance will be almost the same. But simple indexing will, of course, be faster.

+16
source

Access to indexes ( numbers[0] and numbers[numbers.Count - 1] , respectively) is probably faster to a minimum, as First() and Last() require additional calls to the extension methods First() and Last() before accessing list items (depending on their index, again).

+4
source

In the case of List<T> both numbers[0] and numbers.First() will return to the same implementation, so there is no significant difference. The same means Last() .

+2
source

The First() and Last() methods are not actually defined on a List<T> . They are extension methods ; static methods that take a parameter of type IEnumerable<T> , which implements List<T> .

As other answers pointed out, the methods in question do some type checking under the hood and internally use the List<T> indexing feature. This means that in this particular case there will be no difference in performance.

But nowhere does LINQ guarantee these kinds of optimizations. In practice, if you use specific collection types and performance is a problem, never use LINQ methods. They may or may not have to resort to iterating over the collection item on the subject, and you will have to decompile the implementation in order to know.

-1
source

Source: https://habr.com/ru/post/959176/


All Articles