Created
April 25, 2024 22:37
-
-
Save admir-live/118b925e961c97ff37b22857ab4b0f0c to your computer and use it in GitHub Desktop.
Overview of C# Performance Benchmarking Code
This file contains 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
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace YieldVsListPerformanceComparison | |
{ | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<PerformanceBenchmarks>(); | |
} | |
} | |
public class PerformanceBenchmarks | |
{ | |
private const int NumberOfElements = 10000; | |
private List<int> precomputedNumbers; | |
[GlobalSetup] | |
public void InitializeBenchmark() | |
{ | |
precomputedNumbers = new List<int>(); | |
for (var index = 0; index < NumberOfElements; index++) | |
{ | |
precomputedNumbers.Add(index); | |
} | |
} | |
[Benchmark] | |
public void SquareNumbersUsingYield() | |
{ | |
foreach (var number in GenerateNumbersUsingYield(NumberOfElements)) | |
{ | |
var squaredNumber = number * number; | |
} | |
} | |
[Benchmark] | |
public void SquareNumbersUsingList() | |
{ | |
foreach (var number in precomputedNumbers) | |
{ | |
var squaredNumber = number * number; | |
} | |
} | |
private IEnumerable<int> GenerateNumbersUsingYield(int maximumValue) | |
{ | |
for (int index = 0; index < maximumValue; index++) | |
{ | |
yield return index; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment