add a sync.Pool of byte buffers with maximum packet size as cap

ref #217
This commit is contained in:
Lucas Clemente 2016-07-26 15:36:28 +02:00
parent 90aa8cfa95
commit 950e59fa3d
6 changed files with 56 additions and 4 deletions

23
buffer_pool.go Normal file
View file

@ -0,0 +1,23 @@
package quic
import (
"sync"
"github.com/lucas-clemente/quic-go/protocol"
)
var bufferPool sync.Pool
func getPacketBuffer() []byte {
return bufferPool.Get().([]byte)
}
func putPacketBuffer(buf []byte) {
bufferPool.Put(buf[:0])
}
func init() {
bufferPool.New = func() interface{} {
return make([]byte, 0, protocol.MaxPacketSize)
}
}

26
buffer_pool_test.go Normal file
View file

@ -0,0 +1,26 @@
package quic
import (
"github.com/lucas-clemente/quic-go/protocol"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Buffer Pool", func() {
It("returns buffers of correct len and cap", func() {
buf := getPacketBuffer()
Expect(buf).To(HaveLen(0))
Expect(buf).To(HaveCap(int(protocol.MaxPacketSize)))
})
It("zeroes put buffers' length", func() {
for i := 0; i < 1000; i++ {
buf := getPacketBuffer()
putPacketBuffer(buf[0:10])
buf = getPacketBuffer()
Expect(buf).To(HaveLen(0))
Expect(buf).To(HaveCap(int(protocol.MaxPacketSize)))
}
})
})

View file

@ -110,7 +110,7 @@ func (p *packetPacker) packPacket(stopWaitingFrame *frames.StopWaitingFrame, con
}
}
raw := make([]byte, 0, protocol.MaxPacketSize)
raw := getPacketBuffer()
buffer := bytes.NewBuffer(raw)
if responsePublicHeader.WritePublicHeader(buffer, p.version) != nil {

View file

@ -86,7 +86,8 @@ func (s *Server) Serve(conn *net.UDPConn) error {
s.connMutex.Unlock()
for {
data := make([]byte, protocol.MaxPacketSize)
data := getPacketBuffer()
data = data[:protocol.MaxPacketSize]
n, remoteAddr, err := conn.ReadFromUDP(data)
if err != nil {
if strings.HasSuffix(err.Error(), "use of closed network connection") {

View file

@ -531,10 +531,10 @@ func (s *Session) sendPacket() error {
s.delayedAckOriginTime = time.Time{}
err = s.conn.write(packet.raw)
putPacketBuffer(packet.raw)
if err != nil {
return err
}
}
}

View file

@ -27,7 +27,9 @@ type mockConnection struct {
}
func (m *mockConnection) write(p []byte) error {
m.written = append(m.written, p)
b := make([]byte, len(p))
copy(b, p)
m.written = append(m.written, b)
return nil
}