Skip to content

Instantly share code, notes, and snippets.

@bellons91
Created July 9, 2023 13:43
Show Gist options
  • Save bellons91/8d9edecb0c5ee1b86e70f55ee49d3e61 to your computer and use it in GitHub Desktop.
Save bellons91/8d9edecb0c5ee1b86e70f55ee49d3e61 to your computer and use it in GitHub Desktop.
Sort() vs OrderBy() benchmark
#LINQPad optimize+
void Main()
{
var summary = BenchmarkRunner.Run<SortVsOrderbyPerformance>();
}
[MemoryDiagnoser]
public class SortVsOrderbyPerformance
{
private List<int> itemsForSort = new List<int>();
private List<int> itemsForOrderBy = new List<int>();
[Params(10, 100, 1000)]
public int SetSize;
[GlobalSetup]
public void GlobalSetup()
{
Random rd = new Random();
for (int i = 0; i < SetSize; i++)
{
var num = rd.Next();
itemsForOrderBy.Add(num);
itemsForSort.Add(num);
}
}
[Benchmark]
public void TakeWithSort()
{
itemsForSort.Sort();
_ = itemsForSort.Take(5).ToList();
}
[Benchmark]
public void TakeWithOrderBy()
{
_ = itemsForOrderBy.OrderBy(_ => _).Take(5).ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment