Skip to content

Instantly share code, notes, and snippets.

@admir-live
Created May 7, 2024 13:43
Show Gist options
  • Save admir-live/e058065edac0d022226a1b2a0696b4ba to your computer and use it in GitHub Desktop.
Save admir-live/e058065edac0d022226a1b2a0696b4ba to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<PersonAgeSumPerformanceBenchmark>();
[MemoryDiagnoser]
public class PersonAgeSumPerformanceBenchmark
{
private List<Person> _peopleList = default!;
private const int RandomSeed = 12345;
[Params(10, 1_000, 10_000, 100_000)]
public int NumberOfPeople { get; set; }
public class Person
{
public int Age { get; set; }
public Person(int age)
{
Age = age;
}
}
[GlobalSetup]
public void SetupPeopleList()
{
var randomGenerator = new Random(RandomSeed);
_peopleList = new List<Person>(NumberOfPeople);
for (int index = 0; index < NumberOfPeople; index++)
{
_peopleList.Add(new Person(randomGenerator.Next(1, 100)));
}
}
[Benchmark(Baseline = true)]
public int SumAgesUsingForeachLoop()
{
int totalAgeSum = 0;
foreach (Person person in _peopleList)
{
totalAgeSum += person.Age;
}
return totalAgeSum;
}
[Benchmark]
public int SumAgesUsingListForEachMethod()
{
var totalAgeSum = 0;
_peopleList.ForEach(person => IncrementAgeSum(ref totalAgeSum, person.Age));
return totalAgeSum;
static void IncrementAgeSum(ref int sum, int ageToAdd)
{
sum += ageToAdd;
}
}
[Benchmark]
public int SumAgesUsingForLoop()
{
var totalAgeSum = 0;
for (int index = 0; index < _peopleList.Count; index++)
{
totalAgeSum += _peopleList[index].Age;
}
return totalAgeSum;
}
[Benchmark]
public int SumAgesUsingWhileLoop()
{
int totalAgeSum = 0;
int index = 0;
while (index < _peopleList.Count)
{
totalAgeSum += _peopleList[index].Age;
index++;
}
return totalAgeSum;
}
[Benchmark]
public int SumAgesUsingDoWhileLoop()
{
if (_peopleList.Count == 0) return 0;
var totalAgeSum = 0;
var index = 0;
do
{
totalAgeSum += _peopleList[index].Age;
index++;
} while (index < _peopleList.Count);
return totalAgeSum;
}
[Benchmark]
public int SumAgesUsingSpanForeachLoop()
{
var totalAgeSum = 0;
foreach (var person in CollectionsMarshal.AsSpan(_peopleList))
{
totalAgeSum += person.Age;
}
return totalAgeSum;
}
[Benchmark]
public int SumAgesUsingParallelFor()
{
var totalAgeSum = 0;
Parallel.ForEach(_peopleList,
() => 0,
(person, loopState, localAgeSum) => localAgeSum + person.Age,
localAgeSum => Interlocked.Add(ref totalAgeSum, localAgeSum));
return totalAgeSum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment