Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use buffer pools for decompression #2484

Merged
merged 1 commit into from
Jul 25, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions decompress.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"compress/gzip"
"fmt"
"io"
"sync"

snappy "github.com/eapache/go-xerial-snappy"
Expand All @@ -19,6 +18,19 @@ var (
}

gzipReaderPool sync.Pool

bufferPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}

bytesPool = sync.Pool{
New: func() interface{} {
res := make([]byte, 0, 4096)
return &res
},
}
)

func decompress(cc CompressionCodec, data []byte) ([]byte, error) {
Expand All @@ -38,9 +50,17 @@ func decompress(cc CompressionCodec, data []byte) ([]byte, error) {
return nil, err
}

defer gzipReaderPool.Put(reader)
buffer := bufferPool.Get().(*bytes.Buffer)
_, err = buffer.ReadFrom(reader)
// copy the buffer to a new slice with the correct length
// reuse gzipReader and buffer
gzipReaderPool.Put(reader)
res := make([]byte, buffer.Len())
copy(res, buffer.Bytes())
buffer.Reset()
bufferPool.Put(buffer)

return io.ReadAll(reader)
return res, err
case CompressionSnappy:
return snappy.Decode(data)
case CompressionLZ4:
Expand All @@ -50,11 +70,28 @@ func decompress(cc CompressionCodec, data []byte) ([]byte, error) {
} else {
reader.Reset(bytes.NewReader(data))
}
defer lz4ReaderPool.Put(reader)
buffer := bufferPool.Get().(*bytes.Buffer)
_, err := buffer.ReadFrom(reader)
// copy the buffer to a new slice with the correct length
// reuse lz4Reader and buffer
lz4ReaderPool.Put(reader)
res := make([]byte, buffer.Len())
copy(res, buffer.Bytes())
buffer.Reset()
bufferPool.Put(buffer)

return io.ReadAll(reader)
return res, err
case CompressionZSTD:
return zstdDecompress(ZstdDecoderParams{}, nil, data)
buffer := *bytesPool.Get().(*[]byte)
var err error
buffer, err = zstdDecompress(ZstdDecoderParams{}, buffer, data)
// copy the buffer to a new slice with the correct length and reuse buffer
res := make([]byte, len(buffer))
copy(res, buffer)
buffer = buffer[:0]
bytesPool.Put(&buffer)

return res, err
default:
return nil, PacketDecodingError{fmt.Sprintf("invalid compression specified (%d)", cc)}
}
Expand Down