Getting the last value of a collection
You are now going to see how the LINQ method that obtains the last element in the collection is really slow when compared to directly accessing the item by its index. This will be accomplished using benchmarking to measure the performance of different methods:
- Update the
Main
method as follows:static void Main(string[] args) { BenchmarkRunner.Run<LinqPerformance>(); }
- Open the
LinqPerformance
class. - Add the
GetLastPersonVersion1()
method:[Benchmark] public void GetLastPersonVersion1() { var lastPerson = _people.Last(); }
This method gets the last person in the collection using the LINQ-provided Last()
method.
- Add the
GetLastPersonVersion2()
method:[Benchmark] public void GetLastPersonVersion2() { var lastPerson = _people[_people.Count - 1]; }
- Here, we are using the index of the list to extract the...