mirror of
https://github.com/adamhathcock/sharpcompress.git
synced 2026-02-04 05:25:00 +00:00
Use threshold-based ArrayPool strategy for BinaryReaderExtensions
Co-authored-by: adamhathcock <527620+adamhathcock@users.noreply.github.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
@@ -11,18 +12,11 @@ public static class BinaryReaderExtensions
|
||||
{
|
||||
public async Task<byte> ReadByteAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(1);
|
||||
try
|
||||
{
|
||||
await reader
|
||||
.BaseStream.ReadExactAsync(buffer, 0, 1, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return buffer[0];
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
var buffer = new byte[1];
|
||||
await reader
|
||||
.BaseStream.ReadExactAsync(buffer, 0, 1, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return buffer[0];
|
||||
}
|
||||
|
||||
public async Task<byte[]> ReadBytesAsync(
|
||||
@@ -30,6 +24,18 @@ public static class BinaryReaderExtensions
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
// For small allocations, direct allocation is more efficient than pooling
|
||||
// due to ArrayPool overhead and the need to copy data to return array
|
||||
if (count <= 256)
|
||||
{
|
||||
var bytes = new byte[count];
|
||||
await reader
|
||||
.BaseStream.ReadExactAsync(bytes, 0, count, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
// For larger allocations, use ArrayPool to reduce GC pressure
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(count);
|
||||
try
|
||||
{
|
||||
@@ -37,7 +43,7 @@ public static class BinaryReaderExtensions
|
||||
.BaseStream.ReadExactAsync(buffer, 0, count, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var bytes = new byte[count];
|
||||
System.Array.Copy(buffer, 0, bytes, 0, count);
|
||||
Array.Copy(buffer, 0, bytes, 0, count);
|
||||
return bytes;
|
||||
}
|
||||
finally
|
||||
|
||||
Reference in New Issue
Block a user