Skip to content

Add ArrayPoolBufferWriter<T>.ResetWrittenCount() #1051

@bill-poole

Description

@bill-poole

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request 📬A request for new changes to improve functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions