Last active
March 29, 2025 22:29
-
-
Save wallstop/df1ffcac37641c03870d88bed7fdeae2 to your computer and use it in GitHub Desktop.
BenchmarkForLoops.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| namespace Benchmarks; | |
| using BenchmarkDotNet.Attributes; | |
| using BenchmarkDotNet.Configs; | |
| using BenchmarkDotNet.Reports; | |
| using BenchmarkDotNet.Running; | |
| public sealed class Program | |
| { | |
| public static void Main(string[] args) | |
| { | |
| ManualConfig config = ManualConfig.Create(DefaultConfig.Instance); | |
| Summary summary = BenchmarkRunner.Run<Runner>(config); | |
| } | |
| } | |
| public class Runner | |
| { | |
| private readonly int[] _array = Enumerable.Range(0, 10_000_000).ToArray(); | |
| private readonly List<int> _list = Enumerable.Range(0, 10_000_000).ToList(); | |
| [Benchmark] | |
| public long ForLoopArray() | |
| { | |
| long count = 0; | |
| for (int i = 0; i < _array.Length; i++) | |
| { | |
| count += _array[i]; | |
| } | |
| return count; | |
| } | |
| [Benchmark] | |
| public long ForEachLoopArray() | |
| { | |
| long count = 0; | |
| foreach (int t in _array) | |
| { | |
| count += t; | |
| } | |
| return count; | |
| } | |
| [Benchmark] | |
| public long ForLoopList() | |
| { | |
| long count = 0; | |
| for (int i = 0; i < _list.Count; i++) | |
| { | |
| count += _list[i]; | |
| } | |
| return count; | |
| } | |
| [Benchmark] | |
| public long ForEachLoopList() | |
| { | |
| long count = 0; | |
| foreach (int t in _list) | |
| { | |
| count += t; | |
| } | |
| return count; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment