Performance difference between stackalloc, new byte[] and rented buffers in C#

[ShortRunJob]
[MeanColumn]
[MemoryDiagnoser]
[MarkdownExporter]
public class ArrayOps {

    static ArrayPool<byte> Pool = ArrayPool<byte>.Shared;
    
    [Benchmark(Baseline = true)]
    public void NewBuf() {
        byte[] buffer = new byte[10];
        buffer[0] = 10;
    }
    
    [Benchmark]
    public void Stack() {
        Span<byte> buffer = stackalloc byte[10];
        buffer[0] = 10;

    }

    [Benchmark]
    public void Rent() {
        byte[] buffer = Pool.Rent(10);
        buffer[0] = 10;
        Pool.Return(buffer);
    }
}
MethodMeanErrorStdDevRatioRatioSDGen0AllocatedAlloc Ratio
NewBuf4.6338 ns1.4975 ns0.0821 ns1.000.000.009640 B1.00
Stack0.6360 ns0.6726 ns0.0369 ns0.140.01--0.00
Rent20.2033 ns5.3310 ns0.2922 ns4.360.07--0.00

Summary

stackalloc is 7 times faster than new byte[] for small byte arrays, and 28 times faster than using pooled byte arrays.

image-20230815161241292


To contact me, send an email anytime or leave a comment below.