Created
July 9, 2023 13:43
-
-
Save bellons91/8d9edecb0c5ee1b86e70f55ee49d3e61 to your computer and use it in GitHub Desktop.
Sort() vs OrderBy() benchmark
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
#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