Skip to content

Commit 8fa1248

Browse files
morottirmmancom
andauthored
gh-117151: optimize BufferedWriter(), do not buffer writes that are the buffer size (GH-118037)
BufferedWriter() was buffering calls that are the exact same size as the buffer. it's a very common case to read/write in blocks of the exact buffer size. it's pointless to copy a full buffer, it's costing extra memory copy and the full buffer will have to be written in the next call anyway. Co-authored-by: rmorotti <romain.morotti@man.com>
1 parent 23950be commit 8fa1248

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

Modules/_io/bufferedio.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2092,7 +2092,7 @@ _io_BufferedWriter_write_impl(buffered *self, Py_buffer *buffer)
20922092
self->raw_pos = 0;
20932093
}
20942094
avail = Py_SAFE_DOWNCAST(self->buffer_size - self->pos, Py_off_t, Py_ssize_t);
2095-
if (buffer->len <= avail) {
2095+
if (buffer->len <= avail && buffer->len < self->buffer_size) {
20962096
memcpy(self->buffer + self->pos, buffer->buf, buffer->len);
20972097
if (!VALID_WRITE_BUFFER(self) || self->write_pos > self->pos) {
20982098
self->write_pos = self->pos;
@@ -2161,7 +2161,7 @@ _io_BufferedWriter_write_impl(buffered *self, Py_buffer *buffer)
21612161
/* Then write buf itself. At this point the buffer has been emptied. */
21622162
remaining = buffer->len;
21632163
written = 0;
2164-
while (remaining > self->buffer_size) {
2164+
while (remaining >= self->buffer_size) {
21652165
Py_ssize_t n = _bufferedwriter_raw_write(
21662166
self, (char *) buffer->buf + written, buffer->len - written);
21672167
if (n == -1) {

0 commit comments

Comments
 (0)