Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using BenchmarkDotNet.Attributes;
- using BenchmarkDotNet.Running;
- BenchmarkRunner.Run<ForEachVsFor>();
- [RPlotExporter, RankColumn, MemoryDiagnoser]
- public class ForEachVsFor
- {
- private int[] array;
- [Params(10, 100, 1000)]
- public int N;
- [GlobalSetup]
- public void Setup()
- {
- array = Enumerable.Repeat(0, N)
- .Select(i => Random.Shared.Next(1, 10))
- .ToArray();
- }
- [Benchmark(Baseline = true)]
- public int For()
- {
- var total = 0;
- for (var i = 0; i < array.Length; i++)
- {
- total += array[i];
- }
- return total;
- }
- [Benchmark]
- public int Foreach()
- {
- var total = 0;
- foreach (var i in array)
- {
- total += i;
- }
- return total;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement