Skip to content

Commit f4a8de5

Browse files
committed
gh-129005: Align FileIO.readall allocation
Both now use a pre-allocated buffer of length `bufsize`, fill it using a readinto, and have matching "expand buffer" logic. On my machine this takes: `./python -m test -M8g -uall test_largefile -m test_large_read -v` from ~3.7 seconds to ~3.3 seconds
1 parent 41ad2bb commit f4a8de5

File tree

1 file changed

+18
-8
lines changed

1 file changed

+18
-8
lines changed

Lib/_pyio.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1674,22 +1674,32 @@ def readall(self):
16741674
except OSError:
16751675
pass
16761676

1677-
result = bytearray()
1677+
result = bytearray(bufsize)
1678+
bytes_read = 0
16781679
while True:
1679-
if len(result) >= bufsize:
1680-
bufsize = len(result)
1681-
bufsize += max(bufsize, DEFAULT_BUFFER_SIZE)
1680+
if bytes_read >= bufsize:
1681+
# Parallels _io/fileio.c new_buffersize
1682+
if bufsize > 65536:
1683+
addend = bufsize >> 3
1684+
else:
1685+
addend = bufsize + 256
1686+
if addend < DEFAULT_BUFFER_SIZE:
1687+
addend = DEFAULT_BUFFER_SIZE
1688+
bufsize += addend
1689+
result[bytes_read:bufsize] = b'\0'
1690+
assert bufsize - bytes_read > 0, "Should always try and read at least one byte"
16821691
n = bufsize - len(result)
16831692
try:
1684-
chunk = os.read(self._fd, n)
1693+
n = os.readinto(self._fd, memoryview(result)[bytes_read:])
16851694
except BlockingIOError:
1686-
if result:
1695+
if bytes_read > 0:
16871696
break
16881697
return None
1689-
if not chunk: # reached the end of the file
1698+
if n == 0: # reached the end of the file
16901699
break
1691-
result += chunk
1700+
bytes_read += n
16921701

1702+
del result[bytes_read:]
16931703
return bytes(result)
16941704

16951705
def readinto(self, buffer):

0 commit comments

Comments
 (0)