Repository navigation
fix: avoid O(n²) buffer copying in BufferedFile.read - #2690
Open
VenkateswarluNagineni wants to merge 1 commit into
Open
VenkateswarluNagineni wants to merge 1 commit into
VenkateswarluNagineni wants to merge 1 commit into
Conversation
Track a _rbuffer_start offset instead of slicing the buffer on every read. Compact when more than half the buffer has been consumed so memory usage stays bounded. Reading N bytes one byte at a time goes from O(N²) copies to O(N).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this fixes
Closes #2688.
BufferedFile.read(size)compacts the read buffer after every call:Slicing
bytesalways copies. Reading N bytes one byte at a timeallocates and copies roughly
N + (N-1) + … + 1 = O(N²)bytes total.On a large SFTP file this causes multi-second stalls and eventually
memory exhaustion.
Fix
Track a
_rbuffer_startinteger offset instead of slicing on everyread. Compact the underlying
bytesobject (copy once) only when morethan half of it has been consumed — amortised O(1) per byte read.
Changes:
paramiko/file.py: add_rbuffer_start = 0in__init__; replaceslice-after-read with offset arithmetic in
read(); compact inreadline()at entry to keep its logic simple.tests/test_file.py:test_read_small_chunks_linear— fills an8 192-byte buffer then reads it back one byte at a time; asserts
correct data and that the internal buffer stays compact.
Testing