|
| 1 | +using BenchmarkDotNet.Attributes; |
| 2 | +using BenchmarkDotNet.Configs; |
| 3 | +using ZLinq; |
| 4 | + |
| 5 | +namespace Benchmark; |
| 6 | + |
| 7 | +[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] |
| 8 | +public class AnyPredicateWithCapturedLambda |
| 9 | +{ |
| 10 | + [Params(10, 100, 1000, 10000)] |
| 11 | + public int N; |
| 12 | + |
| 13 | + int[] _nums = default!; |
| 14 | + int _target; |
| 15 | + |
| 16 | + [GlobalSetup] |
| 17 | + public void Setup() |
| 18 | + { |
| 19 | + _nums = Enumerable.Range(1, N).ToArray(); |
| 20 | + _target = N / 2; |
| 21 | + } |
| 22 | + |
| 23 | + [Benchmark] |
| 24 | + [BenchmarkCategory("Array")] |
| 25 | + public bool ArrayExists() |
| 26 | + { |
| 27 | + return Array.Exists(_nums, i => i > _target); |
| 28 | + } |
| 29 | + |
| 30 | + [Benchmark] |
| 31 | + [BenchmarkCategory(Categories.ZLinq)] |
| 32 | + public bool ZLinq() |
| 33 | + { |
| 34 | + return _nums.AsValueEnumerable().Any(i => i > _target); |
| 35 | + } |
| 36 | + |
| 37 | + [Benchmark] |
| 38 | + [BenchmarkCategory(Categories.LINQ)] |
| 39 | + public bool Linq() |
| 40 | + { |
| 41 | + return _nums.Any(i => i > _target); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +[GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] |
| 46 | +public class AllPredicateWithCapturedLambda |
| 47 | +{ |
| 48 | + [Params(10, 100, 1000, 10000)] |
| 49 | + public int N; |
| 50 | + |
| 51 | + int[] _nums = default!; |
| 52 | + int _target; |
| 53 | + |
| 54 | + [GlobalSetup] |
| 55 | + public void Setup() |
| 56 | + { |
| 57 | + _nums = Enumerable.Range(1, N).ToArray(); |
| 58 | + _target = N; |
| 59 | + } |
| 60 | + |
| 61 | + [Benchmark] |
| 62 | + [BenchmarkCategory("Array")] |
| 63 | + public bool TrueForAll() |
| 64 | + { |
| 65 | + return Array.TrueForAll(_nums, i => i <= _target); |
| 66 | + } |
| 67 | + |
| 68 | + [Benchmark] |
| 69 | + [BenchmarkCategory(Categories.ZLinq)] |
| 70 | + public bool ZLinq() |
| 71 | + { |
| 72 | + return _nums.AsValueEnumerable().All(i => i <= _target); |
| 73 | + } |
| 74 | + |
| 75 | + [Benchmark] |
| 76 | + [BenchmarkCategory(Categories.LINQ)] |
| 77 | + public bool Linq() |
| 78 | + { |
| 79 | + return _nums.All(i => i <= _target); |
| 80 | + } |
| 81 | +} |
0 commit comments