CommunityToolkit / CommunityToolkit/dotnet
Add ArrayPoolBufferWriter<T>.ResetWrittenCount()
- Dominant language
- C#
- Stars
- 3.8k
- Forks
- 400
- PR merge metrics
- No merged PRs in 30d
Description
### Overview
The `System.Buffers.ArrayBufferWriter` class has a `ResetWrittenCount` method, which resets the write position to zero without clearing the buffer, thus allowing a writer to be reused without clearing the buffer. Without this method, we must create a new `ArrayPoolBufferWriter` instance each time, which carries the GC overhead of allocating the new object, but also the overhead of returning the buffer to the pool, only to immediately get it back again.
### API breakdown
```csharp
namespace CommunityToolkit.HighPerformance.Buffers;
public sealed class ArrayPoolBufferWriter : IBuffer, IMemoryOwner
{
public void ResetWrittenCount() => index = 0;
}
```
### Usage example
```csharp
using var buffer = new ArrayPoolBufferWriter();
using var jsonWriter = new Utf8JsonWriter(buffer);
for (var i = 0; i < 100; i++)
{
// Serialize JSON into buffer.
JsonSerializer.Serialize(jsonWriter, obj, _jsonOptions);
// Compress JSON into output buffer.
compressionStream.Write(buffer.WrittenSpan);
// Reset the JSON writer and buffer.
buffer.ResetWrittenCount();
jsonWriter.Reset();
}
```
### Breaking change?
No
### Alternatives
There is no way to reuse the buffer without incurring the cost of clearing the buffer or cycling the buffer through the array pool.
### Additional context
_No response_
### Help us help you
Yes, I'd like to be assigned to work on this item
Contributor guide
Assessment
This issue has not been assessed yet.