Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created June 19, 2024 21:41
Show Gist options
  • Save admir-live/6605dc9efdf47138e4807d53ff2ab22a to your computer and use it in GitHub Desktop.
Save admir-live/6605dc9efdf47138e4807d53ff2ab22a to your computer and use it in GitHub Desktop.
Getting the last value of a collection
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