Use bytes.Buffer pools for wrappers

This commit is contained in:
9seconds
2018-06-20 08:24:17 +03:00
parent 08ea80680c
commit 9ddf3e147c
2 changed files with 39 additions and 12 deletions
+27
View File
@@ -0,0 +1,27 @@
package wrappers
import (
"bytes"
"sync"
)
var bufPool sync.Pool
func getBuffer() *bytes.Buffer {
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
func putBuffer(buf *bytes.Buffer) {
bufPool.Put(buf)
}
func init() {
bufPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
}
+12 -12
View File
@@ -22,20 +22,20 @@ func (c *StreamCipherReadWriteCloser) Read(p []byte) (n int, err error) {
// Write writes into connection. // Write writes into connection.
func (c *StreamCipherReadWriteCloser) Write(p []byte) (int, error) { func (c *StreamCipherReadWriteCloser) Write(p []byte) (int, error) {
encrypted := make([]byte, len(p)) // This is to decrease an amount of allocations. Unfortunately, escape
// analysis in (at least Golang 1.10) is absolutely not perfect. For
// example, it understands that we want to have a slice locally, right?
// But since slice is effectively 2 ints + uintptr to [number]byte, the
// most heavyweight part is placed in heap.
buf := getBuffer()
defer putBuffer(buf)
buf.Grow(len(p))
buf.Write(p)
encrypted := buf.Bytes()
c.encryptor.XORKeyStream(encrypted, p) c.encryptor.XORKeyStream(encrypted, p)
allWritten := 0
for len(encrypted) > 0 { return c.conn.Write(encrypted)
n, err := c.conn.Write(encrypted)
allWritten += n
if err != nil {
return allWritten, err
}
encrypted = encrypted[n:]
}
return allWritten, nil
} }
// Close closes underlying connection. // Close closes underlying connection.