Advertisement
GeneralGDA

Linq vs Fill

Jun 10th, 2018
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using BenchmarkDotNet.Attributes;
  5. using BenchmarkDotNet.Attributes.Columns;
  6. using BenchmarkDotNet.Attributes.Exporters;
  7. using BenchmarkDotNet.Attributes.Jobs;
  8. using BenchmarkDotNet.Running;
  9.  
  10. namespace Sandbox
  11. {
  12.     [ClrJob] [RPlotExporter, RankColumn]
  13.     public class LinqVsFill
  14.     {
  15.         private string[] _values;
  16.  
  17.         [Params(1000, 10000, 50000, 100000, 150000, 200000)]
  18.         public int N;
  19.  
  20.         [GlobalSetup]
  21.         public void Setup()
  22.         {
  23.             _values = new string[N];
  24.  
  25.             var random = new Random(42);
  26.  
  27.             for (int i = 0; i < N; i++)
  28.             {
  29.                 _values[i] = DateTime.Now.ToString() + random.Next();
  30.             }
  31.         }
  32.  
  33.         private IEnumerable<string> FilterLinq()
  34.         {
  35.             return from a in _values where a.Contains("7") select a;
  36.         }
  37.  
  38.         private List<string> FilterFill()
  39.         {
  40.             var result = new List<string>();
  41.  
  42.             foreach (var a in _values)
  43.             {
  44.                 if (a.Contains("7"))
  45.                 {
  46.                     result.Add(a);
  47.                 }
  48.             }
  49.  
  50.             return result;
  51.         }
  52.  
  53.         [Benchmark]
  54.         public int Linq()
  55.         {
  56.             var count = 0;
  57.  
  58.             foreach (var value in FilterLinq())
  59.             {
  60.                 count += value.Length;
  61.             }
  62.  
  63.             return count;
  64.         }
  65.  
  66.         [Benchmark]
  67.         public int Fill()
  68.         {
  69.             int count = 0;
  70.  
  71.             foreach (var value in FilterFill())
  72.             {
  73.                 count += value.Length;
  74.             }
  75.  
  76.             return count;
  77.         }
  78.     }
  79.  
  80.     public class Program
  81.     {
  82.         public static void Main(string[] args)
  83.         {
  84.             var summary = BenchmarkRunner.Run<LinqVsFill>();
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement