Skip to content

Commit

Permalink
copy header and body of message into the same buffer before sending
Browse files Browse the repository at this point in the history
That way, we don't send a bunch of tiny packets. The extra copy is nothing
compared to that.
  • Loading branch information
Stebalien committed Sep 14, 2018
1 parent 0cf3aeb commit 17259f2
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions multiplex.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ type Multiplex struct {
wrLock sync.Mutex

nstreams chan *Stream
hdrBuf []byte

channels map[streamID]*Stream
chLock sync.Mutex
Expand All @@ -70,7 +69,6 @@ func NewMultiplex(con net.Conn, initiator bool) *Multiplex {
closed: make(chan struct{}),
shutdown: make(chan struct{}),
nstreams: make(chan *Stream, 16),
hdrBuf: make([]byte, 20),
}

go mp.handleIncoming()
Expand Down Expand Up @@ -137,19 +135,19 @@ func (mp *Multiplex) sendMsg(header uint64, data []byte, dl time.Time) error {
return err
}
}
n := binary.PutUvarint(mp.hdrBuf, header)
n += binary.PutUvarint(mp.hdrBuf[n:], uint64(len(data)))
_, err := mp.con.Write(mp.hdrBuf[:n])
buf := mpool.ByteSlicePool.Get(uint32(len(data)) + 20).([]byte)
defer mpool.ByteSlicePool.Put(uint32(cap(buf)), buf)

n := 0
n += binary.PutUvarint(buf[n:], header)
n += binary.PutUvarint(buf[n:], uint64(len(data)))
n += copy(buf[n:], data)

_, err := mp.con.Write(buf[:n])
if err != nil {
return err
}

if len(data) != 0 {
_, err = mp.con.Write(data)
if err != nil {
return err
}
}
if !dl.IsZero() {
if err := mp.con.SetWriteDeadline(time.Time{}); err != nil {
return err
Expand Down

0 comments on commit 17259f2

Please sign in to comment.