Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eliminate []byte(string) allocation under thrift transport #729

Merged
merged 1 commit into from
Apr 1, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion thrift/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type readWriterTransport struct {
io.Reader
readBuf [1]byte
writeBuf [1]byte
strBuf []byte
}

var errNoBytesRead = errors.New("no bytes read")
Expand Down Expand Up @@ -82,7 +83,22 @@ func (t *readWriterTransport) WriteByte(b byte) error {
}

func (t *readWriterTransport) WriteString(s string) (int, error) {
return io.WriteString(t.Writer, s)
// TODO switch to io.StringWriter once we don't need to support < 1.12
type stringWriter interface{ WriteString(string) (int, error) }

if sw, ok := t.Writer.(stringWriter); ok {
return sw.WriteString(s)
}

// This path frequently taken since thrift.TBinaryProtocol calls
// WriteString a lot, but fragmentingWriter does not implement WriteString;
// furthermore it is difficult to add a dual WriteString path to
// fragmentingWriter, since hash checksumming does not accept strings.
//
// Without this, io.WriteString ends up allocating every time.
b := append(t.strBuf[:0], s...)
t.strBuf = b[:0]
return t.Writer.Write(b)
}

// RemainingBytes returns the max number of bytes (same as Thrift's StreamTransport) as we
Expand Down