dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Add ArrayPoolBufferWriter<T>.ResetWrittenCount()

Open bill-poole opened this issue 1 year ago • 0 comments

Overview

The System.Buffers.ArrayBufferWriter<T> 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<T> 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

namespace CommunityToolkit.HighPerformance.Buffers;

public sealed class ArrayPoolBufferWriter<T> : IBuffer<T>, IMemoryOwner<T>
{
    public void ResetWrittenCount() => index = 0;
}

Usage example

using var buffer = new ArrayPoolBufferWriter<byte>();
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

bill-poole avatar Feb 23 '25 07:02 bill-poole