For a network related framework I need a lot of byte[]
buffers to read and write data. When creating a new byte array, the CLR will initialize all values with 0
. For buffers used with streams, this seems to be unnecessary overhead:
var buffer = new byte[65536];
var read = await stream.ReadAsync(buffer, 0, buffer.Length);
Is there a way to create a byte[]
array without initializing all values with 0
in C#? Probably by invoking a malloc
style method? I'm sure this question has been answered, but I didn't find any clues to start with.
Thanks to mjwills link, I stumbled upon the ArrayPool<T>
of System.Buffers:
static void Main(string[] args)
{
var pool = ArrayPool<byte>.Create();
var watch = new Stopwatch();
watch.Start();
Parallel.For(0, 1000000, (i) =>
{
//DoSomethingWithBuffers();
DoSomethingWithPooledBuffers(pool);
});
Console.WriteLine(watch.ElapsedMilliseconds);
}
private static int DoSomethingWithBuffers()
{
var buffer = new byte[65536];
return buffer.Length;
}
private static int DoSomethingWithPooledBuffers(ArrayPool<byte> pool)
{
var buffer = pool.Rent(65536);
var length = buffer.Length;
pool.Return(buffer);
return length;
}
Which makes quite a difference (release mode):