How to use RecyclableMemoryStream in .NET Core


Microsoft.IO.RecyclableMemoryStream is a high-performance library designed to improve application performance when working with streams. It is a replacement for MemoryStream and provides better performance than MemoryStream instances.

You can use RecyclableMemoryStream to eliminate LOH (large object heap) allocations and avoid memory fragmentation and memory leaks. This article talks about the Microsoft.IO.RecyclableMemoryStream library, its purpose, and how it can be used in .NET Core applications to boost application performance.

To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can .

Create a .NET Core console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new .NET Core console application project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. Click Create.

This will create a new .NET Core console application project in Visual Studio 2019. We’ll use this project to work with Microsoft.IO.RecyclableMemoryStream in the subsequent sections of this article.

RecyclableMemoryStream benefits

Microsoft.IO.RecyclableMemoryStream provides the following benefits:

. The following guidelines or best practices should be adhered to when working with RecyclableMemoryStream: 

  1. Set the blockSize, largeBufferMultiple, maxBufferSize, MaximumFreeLargePoolBytes, and MaximumFreeSmallPoolBytes properties to appropriate values.
  2. Dispose of any stream object as soon as you’re done using it.
  3. Never call the ToArray method. 
  4. Avoid calling the GetBuffer method. 

Microsoft.IO.RecyclableMemoryStream is a pooled memory stream allocator that is adept at reducing GC load and improving the performance of your applications. Microsoft.IO.RecyclableMemoryStream takes advantage of pooled buffers to eliminate large object heap (LOH) allocations. It not only avoids memory fragmentation and memory leaks but also provides metrics that can be used for tracking performance.

How to do more in ASP.NET Core:

Copyright © 2020 IDG Communications, Inc.