Skip to content

Commit dbcdb07

Browse files
authored
Use ArrayPool for buffered reading in StreamBox (#1738)
1 parent 63a8819 commit dbcdb07

1 file changed

Lines changed: 12 additions & 7 deletions

File tree

Src/IronPython/Runtime/PythonFileManager.cs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#nullable enable
66

77
using System;
8+
using System.Buffers;
89
using System.Collections.Concurrent;
910
using System.Collections.Generic;
1011
using System.Diagnostics.CodeAnalysis;
@@ -118,14 +119,18 @@ public int ReadInto(IPythonBuffer buffer) {
118119
return _readStream.Read(bytes, 0, buffer.NumBytes());
119120
}
120121

121-
const int chunkSize = 0x400; // 1 KiB
122-
bytes = new byte[chunkSize];
123122
var span = buffer.AsSpan();
124-
for (int pos = 0; pos < span.Length; pos += chunkSize) {
125-
int toRead = Math.Min(chunkSize, span.Length - pos);
126-
int hasRead = _readStream.Read(bytes, 0, toRead);
127-
bytes.AsSpan(0, hasRead).CopyTo(span.Slice(pos));
128-
if (hasRead < toRead) return pos + hasRead;
123+
const int chunkSize = 0x1000; // 4 KiB, default buffer size of FileSteam
124+
bytes = ArrayPool<byte>.Shared.Rent(chunkSize);
125+
try {
126+
for (int pos = 0; pos < span.Length; pos += chunkSize) {
127+
int toRead = Math.Min(chunkSize, span.Length - pos);
128+
int hasRead = _readStream.Read(bytes, 0, toRead);
129+
bytes.AsSpan(0, hasRead).CopyTo(span.Slice(pos));
130+
if (hasRead < toRead) return pos + hasRead;
131+
}
132+
} finally {
133+
ArrayPool<byte>.Shared.Return(bytes);
129134
}
130135
return span.Length;
131136
#endif

0 commit comments

Comments
 (0)