Skip to content

Commit

Permalink
pool BufferedWriter allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
vyzo committed May 8, 2019
1 parent 7fe6340 commit 8d87044
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
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)
}

0 comments on commit 8d87044

Please sign in to comment.