Skip to content

Commit 56bb3d6

Browse files
authored
Use the ArrayPool API in .NET Standard 2.1 or later to reduce the creation of LOH objects. (#1812)
1 parent fc738a1 commit 56bb3d6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/Magick.NET/Helpers/ByteArrayWrapper.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,44 @@
33

44
using System;
55
using System.IO;
6+
#if !NETSTANDARD2_0
7+
using System.Buffers;
8+
#endif
69

710
namespace ImageMagick;
811

912
internal sealed unsafe class ByteArrayWrapper
1013
{
14+
#if !NETSTANDARD2_0
15+
private static readonly ArrayPool<byte> _pool = ArrayPool<byte>.Create(1024 * 1024 * 64, 128);
16+
17+
private byte[] _bytes = _pool.Rent(8192);
18+
#else
1119
private byte[] _bytes = new byte[8192];
20+
#endif
1221
private int _offset = 0;
22+
1323
private int _length = 0;
1424

25+
#if !NETSTANDARD2_0
26+
~ByteArrayWrapper()
27+
=> _pool.Return(_bytes);
28+
29+
public byte[] GetBytes()
30+
{
31+
var result = new byte[_length];
32+
Array.Copy(_bytes, result, _length);
33+
return result;
34+
}
35+
36+
#else
1537
public byte[] GetBytes()
1638
{
1739
ResizeBytes(_length);
1840
return _bytes;
1941
}
2042

43+
#endif
2144
public long Read(IntPtr data, UIntPtr count, IntPtr user_data)
2245
{
2346
if (data == IntPtr.Zero)
@@ -105,6 +128,16 @@ private void EnsureLength(int length)
105128
ResizeBytes(newLength);
106129
}
107130

131+
#if !NETSTANDARD2_0
132+
private void ResizeBytes(int length)
133+
{
134+
var newBytes = _pool.Rent(length);
135+
Array.Copy(_bytes, newBytes, _bytes.Length);
136+
_pool.Return(_bytes);
137+
_bytes = newBytes;
138+
}
139+
#else
108140
private void ResizeBytes(int length)
109141
=> Array.Resize(ref _bytes, length);
142+
#endif
110143
}

0 commit comments

Comments
 (0)