Advertisement
Guest User

Untitled

a guest
Nov 20th, 2021
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.86 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. using BenchmarkDotNet.Attributes;
  5. using BenchmarkDotNet.Running;
  6.  
  7. BenchmarkRunner.Run<ForEachVsFor>();
  8.  
  9. [RPlotExporter, RankColumn, MemoryDiagnoser]
  10. public class ForEachVsFor
  11. {
  12.     private int[] array;
  13.  
  14.     [Params(10, 100, 1000)]
  15.     public int N;
  16.  
  17.     [GlobalSetup]
  18.     public void Setup()
  19.     {
  20.         array = Enumerable.Repeat(0, N)
  21.         .Select(i => Random.Shared.Next(1, 10))
  22.         .ToArray();
  23.     }
  24.  
  25.     [Benchmark(Baseline = true)]
  26.     public int For()
  27.     {
  28.         var total = 0;
  29.         for (var i = 0; i < array.Length; i++)
  30.         {
  31.             total += array[i];
  32.         }
  33.  
  34.         return total;
  35.     }
  36.  
  37.     [Benchmark]
  38.     public int Foreach()
  39.     {
  40.         var total = 0;
  41.         foreach (var i in array)
  42.         {
  43.             total += i;
  44.         }
  45.  
  46.         return total;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement