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

pool BufferedWriter allocations #40

Merged
merged 1 commit into from
May 8, 2019
Merged
Show file tree
Hide file tree
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
5 changes: 3 additions & 2 deletions lazyClient.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package multistream

import (
"bufio"
"fmt"
"io"
"sync"
Expand Down Expand Up @@ -98,7 +97,9 @@ func (l *lazyClientConn) doWriteHandshake() {

// Perform the write handshake but *also* write some extra data.
func (l *lazyClientConn) doWriteHandshakeWithData(extra []byte) int {
buf := bufio.NewWriter(l.con)
buf := getWriter(l.con)
defer putWriter(buf)

for _, proto := range l.protos {
l.werr = delimWrite(buf, []byte(proto))
if l.werr != nil {
Expand Down
21 changes: 20 additions & 1 deletion multistream.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ var ErrTooLarge = errors.New("incoming message was too large")
// the multistream muxers on both sides of a channel can work with each other.
const ProtocolID = "/multistream/1.0.0"

var writerPool = sync.Pool{
New: func() interface{} {
return bufio.NewWriter(nil)
},
}

// HandlerFunc is a user-provided function used by the MultistreamMuxer to
// handle a protocol/stream.
type HandlerFunc func(protocol string, rwc io.ReadWriteCloser) error
Expand Down Expand Up @@ -55,7 +61,9 @@ func writeUvarint(w io.Writer, i uint64) error {
}

func delimWriteBuffered(w io.Writer, mes []byte) error {
bw := bufio.NewWriter(w)
bw := getWriter(w)
defer putWriter(bw)

err := delimWrite(bw, mes)
if err != nil {
return err
Expand Down Expand Up @@ -443,3 +451,14 @@ func (br *byteReader) ReadByte() (byte, error) {
}
return 0, err
}

func getWriter(w io.Writer) *bufio.Writer {
bw := writerPool.Get().(*bufio.Writer)
bw.Reset(w)
return bw
}

func putWriter(bw *bufio.Writer) {
bw.Reset(nil)
writerPool.Put(bw)
}