using System; using System.Collections.Generic; using System.Linq; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Running; public static class EnumerableExtensions { static readonly Func notNullTest = x => x is not null; public static IEnumerable WhereNotNull(this IEnumerable source) where T : class => source.Where((Func)notNullTest)!; public static IEnumerable WhereNotNull(this IEnumerable source) where T : struct => source.Where(x => x.HasValue).Select(x => x!.Value); } public class BenchmarkClass { const int dataLength = 100_000; int?[] intData = new int?[dataLength]; string?[] stringData = new string?[dataLength]; public BenchmarkClass() { var random = new Random(); for (int idx = 0; idx < dataLength; ++idx) { var value = random.Next(100); if (value != 0) { intData[idx] = value; stringData[idx] = value.ToString(); } } } [Benchmark] public void Integer_OfType() => intData.OfType().Consume(new Consumer()); [Benchmark] public void Integer_WhereNotNull() => intData.WhereNotNull().Consume(new Consumer()); [Benchmark] public void String_OfType() => stringData.OfType().Consume(new Consumer()); [Benchmark] public void String_WhereNotNull() => stringData.WhereNotNull().Consume(new Consumer()); } public static class Program { public static void Main() => BenchmarkRunner.Run(); }