Search code examples
c#.netperformancegeneric-handler

Could allocating a byte array be performance-critical?


In my small little file transfer website (this one, running .NET 4.5.1) I'm following the Microsoft Knowledge Base article 812406 to send previously uploaded files from the server to the browser.

Doing performance optimization I was suprised to find that the line

var buffer = new byte[10000];

takes a considerable percentage of time (I'm using Red Gate's ANTS Performance Profiler). The buffer is only allocated once per full download/client.

My questions:

  • Is it good practice to allocate a buffer this way and this size?
  • Any alternatives on allocating a ≈10k buffer?

Update 1:

Thanks to your comments I've seen that the memory is allocated inside the loop, too.

Still, ANTS Profiler only marks that allocation outside of the loop to take that much time, which I honestly do not understand (yet). I have removed the (meaningless) allocation inside the loop.

Update 2:

Having implemented the suggested BufferManager and also reduced the buffer size from 10k down to 4096 (just in case...), my website runs very smooth since days.


Solution

  • Yes. Actually, WCF uses a "buffer manager" to prevent this problem.

    I have been myself developing a network service, and during profiling I found that the allocation of Byte[] buffers was creating a bottleneck. Not only during the allocation, but also the time the processor wasted in the GC was very high. Improvements to reuse those buffers and avoid allocations yield very big performance improvements.

    You can use the BufferManager class to avoid writing your own buffer management strategy.