Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ArrayPoolBufferWriter<T>.ResetWrittenCount() #1051

Open
bill-poole opened this issue Feb 23, 2025 · 0 comments
Open

Add ArrayPoolBufferWriter<T>.ResetWrittenCount() #1051

bill-poole opened this issue Feb 23, 2025 · 0 comments
Labels
feature request 📬 A request for new changes to improve functionality

Comments

@bill-poole
Copy link

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 bill-poole added the feature request 📬 A request for new changes to improve functionality label Feb 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request 📬 A request for new changes to improve functionality
Projects
None yet
Development

No branches or pull requests

1 participant