Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created April 25, 2024 22:37
Show Gist options
  • Save admir-live/118b925e961c97ff37b22857ab4b0f0c to your computer and use it in GitHub Desktop.
Save admir-live/118b925e961c97ff37b22857ab4b0f0c to your computer and use it in GitHub Desktop.
Overview of C# Performance Benchmarking Code
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