Created
March 17, 2024 08:59
-
-
Save megasuperlexa/c59c370a47daa12644e01429cd1183e9 to your computer and use it in GitHub Desktop.
Array pool perf
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
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