Skip to content

Use the ArrayPool API in .NET Standard 2.1 or later to reduce the creation of LOH objects. #1812

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

Merged
merged 16 commits into from
Apr 25, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/Magick.NET/Helpers/ByteArrayWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,44 @@

using System;
using System.IO;
#if !NETSTANDARD2_0
using System.Buffers;
#endif

namespace ImageMagick;

internal sealed unsafe class ByteArrayWrapper
{
#if !NETSTANDARD2_0
private static readonly ArrayPool<byte> _pool = ArrayPool<byte>.Create(1024 * 1024 * 64, 128);

private byte[] _bytes = _pool.Rent(8192);
#else
private byte[] _bytes = new byte[8192];
#endif
private int _offset = 0;

private int _length = 0;

#if !NETSTANDARD2_0
~ByteArrayWrapper()
=> _pool.Return(_bytes);

public byte[] GetBytes()
{
var result = new byte[_length];
Array.Copy(_bytes, result, _length);
return result;
}

#else
public byte[] GetBytes()
{
ResizeBytes(_length);
return _bytes;
}

#endif
public long Read(IntPtr data, UIntPtr count, IntPtr user_data)
{
if (data == IntPtr.Zero)
Expand Down Expand Up @@ -105,6 +128,16 @@ private void EnsureLength(int length)
ResizeBytes(newLength);
}

#if !NETSTANDARD2_0
private void ResizeBytes(int length)
{
var newBytes = _pool.Rent(length);
Array.Copy(_bytes, newBytes, _bytes.Length);
_pool.Return(_bytes);
_bytes = newBytes;
}
#else
private void ResizeBytes(int length)
=> Array.Resize(ref _bytes, length);
#endif
}