Skip to content

Stream.Flush should reuse buffer #438

Closed
@robfig

Description

@robfig

Stream.Flush copies the contents of the stream's buffer to the output, but instead of resetting its buffer to reuse the allocation, it keeps appending to the end of the buffer. For large JSON objects this results in much more allocation than necessary.

// Flush writes any buffered data to the underlying io.Writer.
func (stream *Stream) Flush() error {
	if stream.out == nil {
		return nil
	}
	if stream.Error != nil {
		return stream.Error
	}
	n, err := stream.out.Write(stream.buf)
	if err != nil {
		if stream.Error == nil {
			stream.Error = err
		}
		return err
	}
	stream.buf = stream.buf[n:]  // <--- HERE
	return nil
}

I think the marked line above should instead be

	stream.buf = stream.buf[:0]

Am I missing something?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions