MinMaxBenchmark.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading;
  7. using BenchmarkDotNet.Attributes;
  8. namespace Benchmarks.System.Interactive
  9. {
  10. [MemoryDiagnoser]
  11. public class MinMaxBenchmark
  12. {
  13. [Params(1, 10, 100, 1000, 10000, 100000, 1000000)]
  14. public int N;
  15. private int _store;
  16. private IList<int>? _listStore;
  17. private readonly IComparer<int> _comparer = Comparer<int>.Default;
  18. [Benchmark]
  19. public void Min()
  20. {
  21. Volatile.Write(ref _store, Enumerable.Range(1, N).Min(_comparer));
  22. }
  23. [Benchmark]
  24. public void MinBy()
  25. {
  26. Volatile.Write(ref _listStore, Enumerable.Range(1, N).MinBy(v => -v, _comparer));
  27. }
  28. [Benchmark]
  29. public void Max()
  30. {
  31. Volatile.Write(ref _store, Enumerable.Range(1, N).Max(_comparer));
  32. }
  33. [Benchmark]
  34. public void MaxBy()
  35. {
  36. Volatile.Write(ref _listStore, Enumerable.Range(1, N).MaxBy(v => -v, _comparer));
  37. }
  38. }
  39. }