<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://hashnode.devindran.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 06:07:18 GMT</lastBuildDate><atom:link href="https://hashnode.devindran.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to improve memory allocation when using StackExchange.Redis]]></title><description><![CDATA[Hello, if your code depends on Redis caching and you are using StackExchange.Redis as your middleware for reading and writing, this article may be useful…]]></description><link>https://hashnode.devindran.com/how-to-improve-memory-allocation-when-using-stackexchangeredis</link><guid isPermaLink="true">https://hashnode.devindran.com/how-to-improve-memory-allocation-when-using-stackexchangeredis</guid><category><![CDATA[.NET]]></category><category><![CDATA[C#]]></category><category><![CDATA[Redis]]></category><category><![CDATA[asp.net core]]></category><dc:creator><![CDATA[Devindran Ramadass]]></dc:creator><pubDate>Tue, 23 May 2023 13:11:51 GMT</pubDate><content:encoded><![CDATA[<p>Hello, if your code depends on Redis caching and you are using StackExchange.Redis as your middleware for reading and writing, this article may be useful for you.</p>
<p>If you have used the methods made available by the library, you would notice that in most scenarios, the input and output data type is called RedisValue. It somehow automagically works with most common data types, in most cases byte[] or string.</p>
<p>The most common ways to read and write values that I see published online are as follows:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// write</span>
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = System.Text.Json.JsonSerializer.Serialize(Item);
<span class="hljs-keyword">await</span> _database.StringSetAsync(<span class="hljs-string">"key"</span>, <span class="hljs-keyword">value</span>, TimeSpan.FromMinutes(<span class="hljs-number">5</span>));

<span class="hljs-comment">// read</span>
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = <span class="hljs-keyword">await</span> _database.StringGetAsync(<span class="hljs-string">"key"</span>);
<span class="hljs-keyword">var</span> item = System.Text.Json.JsonSerializer.Deserialize&lt;BenchmarkItems.Item&gt;(<span class="hljs-keyword">value</span>);
</code></pre>
<p>However, working with strings means having to allocate space in the memory. While digging through the code, I found ways to reduce the amount of allocations done while also cutting a bit of time spent. In my previous postings, I demonstrated how to serialize/deserialize directly to streams/buffers using either the RecycleableMemoryStream class or IBufferWriter interface.</p>
<h3 id="heading-writing-to-redis">Writing to Redis</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> RecyclableMemoryStreamManager _ms = <span class="hljs-keyword">new</span>();

<span class="hljs-comment">// recyclable memory stream</span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> stream = _ms.GetStream();
System.Text.Json.JsonSerializer.Serialize(stream, Item);
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = StackExchange.Redis.RedisValue.CreateFrom(stream);
<span class="hljs-keyword">await</span> _database.StringSetAsync(<span class="hljs-string">"key"</span>, <span class="hljs-keyword">value</span>, TimeSpan.FromMinutes(<span class="hljs-number">5</span>));

<span class="hljs-comment">// buffer writer</span>
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> buffer= <span class="hljs-keyword">new</span> ArrayPoolBufferWriter&lt;<span class="hljs-keyword">byte</span>&gt;();
<span class="hljs-keyword">var</span> writer = <span class="hljs-keyword">new</span> Utf8JsonWriter(buffer);
System.Text.Json.JsonSerializer.Serialize(writer, Item);
<span class="hljs-keyword">await</span> _database.StringSetAsync(<span class="hljs-string">"key"</span>, buffer.WrittenMemory, TimeSpan.FromMinutes(<span class="hljs-number">5</span>));
</code></pre>
<p>In the first approach, there is a little-known approach to create a RedisValue from the stream which can be used to keep allocation to a minimum. In the benchmark below you can see that it cut down the allocated space of a 70KB Json file by about half.</p>
<pre><code class="lang-csharp">|                     Method |     Mean |    Error |   StdDev | Allocated |
|--------------------------- |---------:|---------:|---------:|----------:|
|                 Set_String | <span class="hljs-number">12.70</span> ms | <span class="hljs-number">0.115</span> ms | <span class="hljs-number">0.102</span> ms |   <span class="hljs-number">8.95</span> KB |
| Set_RecyclableMemoryStream | <span class="hljs-number">12.82</span> ms | <span class="hljs-number">0.087</span> ms | <span class="hljs-number">0.082</span> ms |   <span class="hljs-number">3.86</span> KB |
|           Set_BufferWriter | <span class="hljs-number">12.36</span> ms | <span class="hljs-number">0.105</span> ms | <span class="hljs-number">0.093</span> ms |   <span class="hljs-number">3.71</span> KB |
</code></pre>
<h3 id="heading-reading-from-redis">Reading from Redis</h3>
<p>When reading from Redis, I found a method provided by the library called StringGetLeaseAsync which returned a type of Lease which is an implementation of IMemoryOwner&lt;T&gt;. The rationale here is that by exposing the response as IMemoryOwner, the caller can then decide when to dispose of the object.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> memory = <span class="hljs-keyword">await</span> _database.StringGetLeaseAsync(<span class="hljs-string">"key"</span>);
<span class="hljs-keyword">var</span> item = System.Text.Json.JsonSerializer.Deserialize&lt;BenchmarkItems.Item&gt;(memory.Span);
</code></pre>
<p>In benchmarks, I noticed half the allocation and better overall performance.</p>
<pre><code class="lang-csharp">|                     Method |     Mean |    Error |   StdDev | Allocated |
|--------------------------- |---------:|---------:|---------:|----------:|
|                 Get_String | <span class="hljs-number">14.15</span> ms | <span class="hljs-number">0.099</span> ms | <span class="hljs-number">0.088</span> ms |  <span class="hljs-number">15.98</span> KB |
|                  Get_Lease | <span class="hljs-number">11.76</span> ms | <span class="hljs-number">0.128</span> ms | <span class="hljs-number">0.120</span> ms |   <span class="hljs-number">6.81</span> KB |
</code></pre>
<p>Note: I did rerun the same tests with a 2MB file which showed consistent results as well as ensuring no Gen2 heap allocation as compared to the standard approach, but pushing large content to Redis is considered an anti-pattern so I don't think this is applicable for this article.</p>
<p>As usual, I hope this helps improve your code and I hope to learn more from anyone who may have better suggestions on how to read/write with Redis. Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[How to improve memory allocation when creating HttpContent]]></title><description><![CDATA[In almost every application created in .NET, there will be a use case for making an outgoing HTTP call to an external resource. For some of these calls…]]></description><link>https://hashnode.devindran.com/how-to-improve-memory-allocation-when-creating-httpcontent</link><guid isPermaLink="true">https://hashnode.devindran.com/how-to-improve-memory-allocation-when-creating-httpcontent</guid><category><![CDATA[C#]]></category><category><![CDATA[memory-management]]></category><category><![CDATA[.NET]]></category><category><![CDATA[http]]></category><dc:creator><![CDATA[Devindran Ramadass]]></dc:creator><pubDate>Wed, 17 May 2023 03:03:43 GMT</pubDate><content:encoded><![CDATA[<p>In almost every application created in .NET, there will be a use case for making an outgoing HTTP call to an external resource. For some of these calls, especially when using POST and PUT verbs, a payload is usually attached to the HttpRequest object, most often in the form of a serialized JSON string.</p>
<p>By default, the legacy implementation for creating such content would be to leverage the ever-popular Newtonsoft.Json library. A typical example of such code would look something like this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> jsonData = JsonConvert.SerializeObject(myContent);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> content = <span class="hljs-keyword">new</span> StringContent(jsonData, Encoding.UTF8, <span class="hljs-string">"application/json"</span>);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> request = <span class="hljs-keyword">new</span> HttpRequestMessage();
request.RequestUri = <span class="hljs-keyword">new</span> Uri(<span class="hljs-string">"https://httpbin.org/post"</span>);
request.Method = HttpMethod.Post;
request.Content = content;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.SendAsync(request);
</code></pre>
<p>In more recent versions of .NET, the switch to using System.Text.Json for serialization has seen an increase in use due to the improved performance brought by the library. In larger payloads, we can see 3x performance gains by using System.Text.Json as the serializer.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> jsonData = System.Text.Json.JsonSerializer.Serialize(myContent);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> content = <span class="hljs-keyword">new</span> StringContent(jsonData, Encoding.UTF8, <span class="hljs-string">"application/json"</span>);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> request = <span class="hljs-keyword">new</span> HttpRequestMessage();
request.RequestUri = <span class="hljs-keyword">new</span> Uri(<span class="hljs-string">"https://httpbin.org/post"</span>);
request.Method = HttpMethod.Post;
request.Content = content;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.SendAsync(request);
</code></pre>
<h3 id="heading-arraypoolbufferwriter-and-readonlymemorycontent">ArrayPoolBufferWriter and ReadOnlyMemoryContent</h3>
<p>However, for this article, as you can see from the examples above, the way the code is written is mostly similar except for the serializer used. In the benchmarks shown below, you will see that when dealing with larger payloads, both approaches end up allocating to the Gen2 heap, which is a common problem for high-performance applications as most of us already know by now.</p>
<p>With the introduction of access to the System.Buffers namespace, more toolkits are being developed to enhance existing functionalities using Buffers and Pipelines. A common example is the <a target="_blank" href="https://www.nuget.org/packages/CommunityToolkit.HighPerformance">CommunityToolkit.HighPerformance</a> package.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> CommunityToolkit.HighPerformance.Buffers.ArrayPoolBufferWriter&lt;<span class="hljs-keyword">byte</span>&gt; buffer = <span class="hljs-keyword">new</span>();
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> writer = <span class="hljs-keyword">new</span> Utf8JsonWriter(buffer);
<span class="hljs-keyword">var</span> options = <span class="hljs-keyword">new</span> JsonSerializerOptions { }; <span class="hljs-comment">// Putting this here as an example only. Don't declare this inline as it prevents caching</span>
System.Text.Json.JsonSerializer.Serialize(writer, myContent, options);
writer.Flush();
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> content = <span class="hljs-keyword">new</span> ReadOnlyMemoryContent(buffer.WrittenMemory);
content.Headers.Add(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/json"</span>);

<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> request = <span class="hljs-keyword">new</span> HttpRequestMessage();
request.RequestUri = <span class="hljs-keyword">new</span> Uri(<span class="hljs-string">"https://httpbin.org/post"</span>);
request.Method = HttpMethod.Post;
request.Content = content;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.SendAsync(request);
</code></pre>
<p>Using the <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/system.net.http.readonlymemorycontent">ReadOnlyMemoryContent</a> provided by System.Net.Http in addition to the various IBufferWriter implementations provided by the HighPerformance toolkit, we can leverage the ReadOnlyMemory object to create a HttpContent that does not allocate to the heap.</p>
<p>In the benchmark below, we can see that using this approach makes no allocation to Gen0, Gen1 or Gen2 while maintaining the speed provided by the native System.Text.Json approach.</p>
<pre><code class="lang-csharp">|                Method |      Mean |     Error |    StdDev |     Gen0 |     Gen1 |     Gen2 |  Allocated |
|---------------------- |----------:|----------:|----------:|---------:|---------:|---------:|-----------:|
|              Baseline | <span class="hljs-number">21.284</span> ms | <span class="hljs-number">0.3535</span> ms | <span class="hljs-number">0.2952</span> ms | <span class="hljs-number">968.7500</span> | <span class="hljs-number">968.7500</span> | <span class="hljs-number">968.7500</span> | <span class="hljs-number">7183.69</span> KB |
|        SystemTextJson |  <span class="hljs-number">8.468</span> ms | <span class="hljs-number">0.1693</span> ms | <span class="hljs-number">0.4308</span> ms | <span class="hljs-number">375.0000</span> | <span class="hljs-number">375.0000</span> | <span class="hljs-number">375.0000</span> | <span class="hljs-number">3193.51</span> KB |
| ReadOnlyMemoryContent |  <span class="hljs-number">8.124</span> ms | <span class="hljs-number">0.1486</span> ms | <span class="hljs-number">0.2679</span> ms |        - |        - |        - |   <span class="hljs-number">30.15</span> KB |
</code></pre>
<p>The great thing about this approach is that it also works with other common serializers such as MessagePack and Protobuf.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// protobuf</span>
<span class="hljs-keyword">using</span> CommunityToolkit.HighPerformance.Buffers.ArrayPoolBufferWriter&lt;<span class="hljs-keyword">byte</span>&gt; buffer = <span class="hljs-keyword">new</span>();
ProtoBuf.Serializer.Serialize(buffer, myContent);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> content = <span class="hljs-keyword">new</span> ReadOnlyMemoryContent(buffer.WrittenMemory);
content.Headers.Add(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/messagepack"</span>);

<span class="hljs-comment">// messagepack</span>
<span class="hljs-keyword">using</span> CommunityToolkit.HighPerformance.Buffers.ArrayPoolBufferWriter&lt;<span class="hljs-keyword">byte</span>&gt; buffer = <span class="hljs-keyword">new</span>();
MessagePack.MessagePackSerializer.Serialize(buffer, myContent);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> content = <span class="hljs-keyword">new</span> ReadOnlyMemoryContent(buffer.WrittenMemory);
content.Headers.Add(<span class="hljs-string">"Content-Type"</span>, <span class="hljs-string">"application/protobuf"</span>);
</code></pre>
<p>I feel that this is one of the many great features provided by .NET that has not been marketed properly as I am not able to find any reference to its usage online. Hope this article helps to drive adoption.</p>
<p><strong>UPDATE</strong>: After posting this on <a target="_blank" href="https://www.reddit.com/r/csharp/comments/13jpkkf/how_to_improve_memory_allocation_when_creating/">Reddit</a> I received some feedback and great suggestions on other ways to achieve the same result, so I decided to add those to this my benchmark and reran the scripts. I also decided to break down the test into 2 runs, one with a standard Json payload (70KB) and another with my original large payload (2MB).</p>
<h3 id="heading-recyclablememorystream-with-streamcontent">RecyclableMemoryStream with StreamContent</h3>
<p>I've always been a fan of the <a target="_blank" href="https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream">RecyclableMemoryStreamManager</a> library and using this with a StreamContent proved to be great for both small and large size payloads.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> RecyclableMemoryStreamManager _recycle = <span class="hljs-keyword">new</span>();
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">RecyclableStreamAndStreamContent</span>(<span class="hljs-params"></span>)</span>
{
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> stream = _recycle.GetStream();
System.Text.Json.JsonSerializer.Serialize(stream, Item);
stream.Seek(<span class="hljs-number">0</span>, SeekOrigin.Begin);
<span class="hljs-keyword">using</span> HttpContent content = <span class="hljs-keyword">new</span> StreamContent(stream);
content.Headers.ContentType = <span class="hljs-keyword">new</span> MediaTypeHeaderValue(<span class="hljs-string">"application/json"</span>);
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> request = <span class="hljs-keyword">new</span> HttpRequestMessage();
request.RequestUri = _uri;
request.Method = HttpMethod.Post;
request.Content = content;
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
</code></pre>
<h3 id="heading-postasjsonasync">PostAsJsonAsync</h3>
<p>A similar suggestion was to just use the built-in functionality provided by .NET which optimised the HttpContent creation during the network transfer.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">PostAsJsonAsync</span>(<span class="hljs-params"></span>)</span>
{
<span class="hljs-keyword">using</span> <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Client.PostAsJsonAsync(_uri, Item);
response.EnsureSuccessStatusCode();
}
</code></pre>
<h3 id="heading-results">Results</h3>
<pre><code class="lang-csharp">|                                    Method |     Mean |    Error |   StdDev |   Gen0 | Allocated |
|------------------------------------------ |---------:|---------:|---------:|-------:|----------:|
|          RecyclableStreamAndStreamContent | <span class="hljs-number">733.1</span> us | <span class="hljs-number">19.63</span> us | <span class="hljs-number">57.58</span> us | <span class="hljs-number">0.9766</span> |   <span class="hljs-number">7.09</span> KB |
|                           PostAsJsonAsync | <span class="hljs-number">970.6</span> us | <span class="hljs-number">21.43</span> us | <span class="hljs-number">62.51</span> us |      - |   <span class="hljs-number">7.08</span> KB |
|      SystemTextJson_ReadOnlyMemoryContent | <span class="hljs-number">962.0</span> us | <span class="hljs-number">28.02</span> us | <span class="hljs-number">80.40</span> us |      - |   <span class="hljs-number">6.86</span> KB |
|            Protobuf_ReadOnlyMemoryContent | <span class="hljs-number">788.1</span> us | <span class="hljs-number">15.31</span> us | <span class="hljs-number">17.63</span> us | <span class="hljs-number">0.9766</span> |   <span class="hljs-number">5.35</span> KB |
| Protobuf_RecyclableStreamAndStreamContent | <span class="hljs-number">767.8</span> us | <span class="hljs-number">15.03</span> us | <span class="hljs-number">34.54</span> us | <span class="hljs-number">0.9766</span> |   <span class="hljs-number">5.75</span> KB |
</code></pre>
<p>For the first iteration (small payload), we see almost similar results for all 3 options. I also included Protobuf serialization to see if we get the same benefits by using StreamContent and the results show almost similar outcomes.</p>
<p>On the 2nd run using the much larger payload, we see a clear winner with StreamContent.</p>
<pre><code class="lang-csharp">|                                    Method |      Mean |     Error |    StdDev | Allocated |
|------------------------------------------ |----------:|----------:|----------:|----------:|
|          RecyclableStreamAndStreamContent | <span class="hljs-number">28.654</span> ms | <span class="hljs-number">1.1542</span> ms | <span class="hljs-number">3.3670</span> ms |  <span class="hljs-number">25.21</span> KB |
|                               JsonContent | <span class="hljs-number">36.039</span> ms | <span class="hljs-number">1.0074</span> ms | <span class="hljs-number">2.9226</span> ms |  <span class="hljs-number">21.55</span> KB |
|      SystemTextJson_ReadOnlyMemoryContent | <span class="hljs-number">34.717</span> ms | <span class="hljs-number">0.6902</span> ms | <span class="hljs-number">1.7443</span> ms |  <span class="hljs-number">21.32</span> KB |
|            Protobuf_ReadOnlyMemoryContent |  <span class="hljs-number">9.723</span> ms | <span class="hljs-number">0.1953</span> ms | <span class="hljs-number">0.5312</span> ms |   <span class="hljs-number">2.85</span> KB |
| Protobuf_RecyclableStreamAndStreamContent |  <span class="hljs-number">5.273</span> ms | <span class="hljs-number">0.1054</span> ms | <span class="hljs-number">0.2443</span> ms |    <span class="hljs-number">2.8</span> KB |
</code></pre>
<p>The benefits of using the RecyclableStream and StreamContent is that you can use it with other serializers like Protobuf to get faster performance compared to Json with dealing with large objects, assuming you don't optimize fully by going with gRPC.</p>
<p>I am however interested to dig deeper into why the System.Buffers approach which Microsoft says should give much better performance compared to Streams is not showing the supposed gains it should. If you have any idea on this I'm interested to know more.</p>
<p>Please join the discussion on <a target="_blank" href="https://www.reddit.com/r/csharp/comments/13jpkkf/how_to_improve_memory_allocation_when_creating/">Reddit</a> if you have insights you wish to share. Thanks for reading this posting.</p>
]]></content:encoded></item><item><title><![CDATA[RecyclableStreamManager vs MemoryStreams]]></title><description><![CDATA[Hi, in this article, I will discuss the common pitfalls developers encounter while using MemoryStreams and how a little-known library from Microsoft can…]]></description><link>https://hashnode.devindran.com/recyclablestreammanager-vs-memorystreams</link><guid isPermaLink="true">https://hashnode.devindran.com/recyclablestreammanager-vs-memorystreams</guid><category><![CDATA[.NET]]></category><category><![CDATA[.net core]]></category><category><![CDATA[.net 6.0]]></category><category><![CDATA[.NET 7]]></category><category><![CDATA[memory-management]]></category><dc:creator><![CDATA[Devindran Ramadass]]></dc:creator><pubDate>Mon, 23 Jan 2023 14:47:51 GMT</pubDate><content:encoded><![CDATA[<p>Hi, in this article, I will discuss the common pitfalls developers encounter while using MemoryStreams and how a little-known library from Microsoft can help address this issue.</p>
<p><a target="_blank" href="https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream">Microsoft.IO.RecyclableMemoryStream</a></p>
<p>Although it was introduced back in 2015 to be used in .NET Framework, this library only started to gain traction in .NET Core which is widely used in small containerized (docker/kubernetes) applications where smaller memory allocation can see issues with memory leaks.</p>
<p>Described as "A library to provide pooling for .NET MemoryStream objects to improve application performance, especially in the area of garbage collection", the focus of the library is to ensure large streams do not tax the Garbage Collector by allocating the objects to the Gen 2 heap, thereby improving performance and reducing overall memory consumption.</p>
<h3 id="heading-memory-stream">Memory Stream</h3>
<p>In a typical scenario, the best practice for using MemoryStreams is to dispose it after its usage is complete. This is typically done by wrapping it around a using block.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">byte</span>[] <span class="hljs-title">SerializeWithStream</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> memoryStream = <span class="hljs-keyword">new</span> MemoryStream())
    {
        JsonSerializer.Serialize(memoryStream, Item);
        <span class="hljs-keyword">var</span> bytes = memoryStream.ToArray();
        <span class="hljs-keyword">return</span> bytes;
    }
}

<span class="hljs-keyword">public</span> BenchmarkItems.<span class="hljs-function">Item <span class="hljs-title">DeserializeWithStream</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> memoryStream = <span class="hljs-keyword">new</span> MemoryStream(Bytes))
    {
        <span class="hljs-keyword">return</span> JsonSerializer.Deserialize&lt;BenchmarkItems.Item&gt;(memoryStream);
    }
}
</code></pre>
<h3 id="heading-recyclable-memory-stream">Recyclable Memory Stream</h3>
<p>With RecyclableStreams, it's advised to declare the manager as a static or singleton to avoid multiple instances of the manager running at a given time which beats the purpose of having a shared pool to hold the buffers.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> RecyclableMemoryStreamManager recyclableMemoryStream = <span class="hljs-keyword">new</span> RecyclableMemoryStreamManager();
</code></pre>
<p>The actual code looks almost similar to the conventional MemoryStream.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">byte</span>[] <span class="hljs-title">BenchmarkWithStreamManager</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> memoryStream = recyclableMemoryStream.GetStream())
    {
        JsonSerializer.Serialize(memoryStream, Item);
        <span class="hljs-keyword">var</span> bytes = memoryStream.ToArray();
        <span class="hljs-keyword">return</span> bytes;
    }
}

<span class="hljs-keyword">public</span> BenchmarkItems.<span class="hljs-function">Item <span class="hljs-title">DeserializeWithStreamManager</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">using</span> (<span class="hljs-keyword">var</span> memoryStream = recyclableMemoryStream.GetStream(Bytes))
    {
        <span class="hljs-keyword">return</span> JsonSerializer.Deserialize&lt;BenchmarkItems.Item&gt;(memoryStream);
    }
}
</code></pre>
<h3 id="heading-benchmarks">Benchmarks</h3>
<p>The recyclable stream really shines when dealing with larger objects, for example, a large text object to be serialized/deserialized. For this example, I will be using a 2MB JSON data which under normal circumstances will end up on the Gen2 heap taking up valuable space allocated to the instance.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Method</td><td>Mean</td><td>Error</td><td>StdDev</td><td>Gen0</td><td>Gen1</td><td>Gen2</td><td>Allocated</td></tr>
</thead>
<tbody>
<tr>
<td>SerializeWithStream</td><td>8.653 ms</td><td>0.2689 ms</td><td>0.7800 ms</td><td>718.7500</td><td>687.5000</td><td>687.5000</td><td>4.65 MB</td></tr>
<tr>
<td>BenchmarkWithStreamManager</td><td>7.500 ms</td><td>0.2607 ms</td><td>0.7521 ms</td><td>171.8750</td><td>171.8750</td><td>171.8750</td><td>1.05 MB</td></tr>
<tr>
<td>DeserializeWithStream</td><td>11.803 ms</td><td>0.2345 ms</td><td>0.5098 ms</td><td>234.3750</td><td>218.7500</td><td>-</td><td>1.41 MB</td></tr>
<tr>
<td>DeserializeWithStreamManager</td><td>11.986 ms</td><td>0.3047 ms</td><td>0.8985 ms</td><td>234.3750</td><td>218.7500</td><td>-</td><td>1.41 MB</td></tr>
</tbody>
</table>
</div><h3 id="heading-analysis">Analysis</h3>
<p>As you can see from the above benchmark, using the Recyclable Stream Manager improves performance slightly, but the Gen2 allocation is significantly less than using a standard MemoryStream. The reason we are even seeing this is because the test code uses .ToArray() to quickly return the byte array. In future posts, I will describe how to further optimize this.</p>
]]></content:encoded></item></channel></rss>