Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is the RecyclableMemoryStream class. For this one I’m cheating a little bit as it is not part of the .NET Framework directly but released as a separate NuGet package by the Bing team.
What is it?
Microsoft.IO.RecyclableMemoryStream is a drop-in MemoryStream replacement with superior behavior for performance-critical systems. In particular it is optimized to do the following:
- Eliminate Large Object Heap allocations by using pooled buffers
- Incur far fewer gen 2 GCs, and spend far less time paused due to GC
- Avoid memory leaks by having a bounded pool size
- Avoid memory fragmentation
- Provide excellent debuggability
- Provide metrics for performance tracking
The code looks kinda boring as it uses the same semantics as the built-in MemoryStream class:
This file contains 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
var sourceBuffer = new byte[]{0,1,2,3,4,5,6,7}; | |
var manager = new RecyclableMemoryStreamManager(); | |
using (var stream = manager.GetStream()) | |
{ | |
stream.Write(sourceBuffer, 0, sourceBuffer.Length); | |
} |
More information: http://www.philosophicalgeek.com/2015/02/06/announcing-microsoft-io-recycablememorystream/