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);
    }
}
Method Mean Error StdDev Ratio RatioSD Gen0 Allocated Alloc Ratio
NewBuf 4.6338 ns 1.4975 ns 0.0821 ns 1.00 0.00 0.0096 40 B 1.00
Stack 0.6360 ns 0.6726 ns 0.0369 ns 0.14 0.01 - - 0.00
Rent 20.2033 ns 5.3310 ns 0.2922 ns 4.36 0.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.