Created
June 19, 2024 21:41
-
-
Save admir-live/6605dc9efdf47138e4807d53ff2ab22a to your computer and use it in GitHub Desktop.
Getting the last value of a collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using System.Collections.Generic; | |
using System.Linq; | |
using BenchmarkDotNet.Order; | |
// Represents a person with an ID and a Name | |
public class Person | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
[MemoryDiagnoser, RankColumn, Orderer(SummaryOrderPolicy.FastestToSlowest)] | |
public class LinqPerformanceBenchmark | |
{ | |
private List<Person> _personList; | |
public LinqPerformanceBenchmark() | |
{ | |
_personList = new List<Person>(); | |
for (int personIndex = 0; personIndex < 100_000; personIndex++) | |
{ | |
_personList.Add(new Person { Id = personIndex, Name = "Person" + personIndex }); | |
} | |
} | |
[Benchmark] | |
public void RetrieveLastPersonUsingLinqLastMethod() | |
{ | |
Person lastPersonUsingLinq = _personList.Last(); | |
} | |
[Benchmark] | |
public void RetrieveLastPersonUsingIndexer() | |
{ | |
Person lastPersonUsingIndexer = _personList[^1]; | |
} | |
} | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<LinqPerformanceBenchmark>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment