Skip to content

Instantly share code, notes, and snippets.

@megasuperlexa
Created March 17, 2024 08:59
Show Gist options
  • Save megasuperlexa/c59c370a47daa12644e01429cd1183e9 to your computer and use it in GitHub Desktop.
Save megasuperlexa/c59c370a47daa12644e01429cd1183e9 to your computer and use it in GitHub Desktop.
Array pool perf
using System.Buffers;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
public class Program
{
private static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<PoolBench>();
}
[MemoryDiagnoser]
public class PoolBench
{
int Threads = 16;
int Iterations = 64 * 1024;
int ArraySize = 1024;
[Benchmark]
public void ArrayPool()
{
var pool = ArrayPool<byte>.Shared;
var tasks = new Task[Threads];
for (int i = 0; i < Threads; i++)
{
tasks[i] = Task.Run(() =>
{
for (int j = 0; j < Iterations; j++)
{
var arr = pool.Rent(ArraySize);
Random.Shared.NextBytes(arr);
pool.Return(arr);
}
});
}
Task.WaitAll(tasks);
}
[Benchmark]
public void HeapArray()
{
var tasks = new Task[Threads];
for (int i = 0; i < Threads; i++)
{
tasks[i] = Task.Run(() =>
{
for (int j = 0; j < Iterations; j++)
{
var arr = new byte[ArraySize];
Random.Shared.NextBytes(arr);
}
});
}
Task.WaitAll(tasks);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment