Use sync.pool for decode buffer

This commit is contained in:
Ye Yin 2016-09-12 15:10:11 +08:00 committed by Matt Joiner
parent d4e30f84f2
commit d3963eedfd
2 changed files with 22 additions and 1 deletions

View File

@ -698,9 +698,16 @@ func (c *connection) lastHelpful() (ret time.Time) {
func (c *connection) mainReadLoop() error {
t := c.t
cl := t.cl
pool := &sync.Pool{
New: func() interface{} {
return make([]byte, t.chunkSize)
},
}
decoder := pp.Decoder{
R: bufio.NewReader(c.rw),
MaxLength: 256 * 1024,
Pool: pool,
}
for {
cl.mu.Unlock()
@ -774,6 +781,9 @@ func (c *connection) mainReadLoop() error {
err = c.peerSentHaveNone()
case pp.Piece:
cl.downloadedChunk(t, c, &msg)
if len(msg.Piece) == int(t.chunkSize) {
pool.Put(msg.Piece)
}
case pp.Extended:
switch msg.ExtendedID {
case pp.HandshakeExtendedID:

View File

@ -8,6 +8,7 @@ import (
"fmt"
"io"
"io/ioutil"
"sync"
)
type (
@ -123,6 +124,7 @@ func (msg Message) MarshalBinary() (data []byte, err error) {
type Decoder struct {
R *bufio.Reader
Pool *sync.Pool
MaxLength Integer // TODO: Should this include the length header or not?
}
@ -197,7 +199,16 @@ func (d *Decoder) Decode(msg *Message) (err error) {
if err != nil {
break
}
msg.Piece, err = ioutil.ReadAll(r)
//msg.Piece, err = ioutil.ReadAll(r)
b := d.Pool.Get().([]byte)
n, err := io.ReadFull(r, b)
if err != nil {
if err != io.ErrUnexpectedEOF || n != int(length-9) {
return err
}
b = b[0:n]
}
msg.Piece = b
case Extended:
msg.ExtendedID, err = r.ReadByte()
if err != nil {