Reuse string buffer in stringTuples.Swap (#654)

* Reuse string buffer when swapping stringTuples

This reduces the allocs of WriteLabelIndex significantly.

Signed-off-by: Ganesh Vernekar <cs15btech11018@iith.ac.in>

* Fix review comments

Signed-off-by: Ganesh Vernekar <cs15btech11018@iith.ac.in>

* Add CHANGELOG entry

Signed-off-by: Ganesh Vernekar <cs15btech11018@iith.ac.in>
This commit is contained in:
Ganesh Vernekar 2019-07-10 11:58:28 +05:30 committed by GitHub
parent b1cd829030
commit b5b8c9200c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -955,25 +955,30 @@ func (r *Reader) LabelNames() ([]string, error) {
type stringTuples struct {
length int // tuple length
entries []string // flattened tuple entries
swapBuf []string
}
func NewStringTuples(entries []string, length int) (*stringTuples, error) {
if len(entries)%length != 0 {
return nil, errors.Wrap(encoding.ErrInvalidSize, "string tuple list")
}
return &stringTuples{entries: entries, length: length}, nil
return &stringTuples{
entries: entries,
length: length,
}, nil
}
func (t *stringTuples) Len() int { return len(t.entries) / t.length }
func (t *stringTuples) At(i int) ([]string, error) { return t.entries[i : i+t.length], nil }
func (t *stringTuples) Swap(i, j int) {
c := make([]string, t.length)
copy(c, t.entries[i:i+t.length])
if t.swapBuf == nil {
t.swapBuf = make([]string, t.length)
}
copy(t.swapBuf, t.entries[i:i+t.length])
for k := 0; k < t.length; k++ {
t.entries[i+k] = t.entries[j+k]
t.entries[j+k] = c[k]
t.entries[j+k] = t.swapBuf[k]
}
}