Skip to content

Commit

Permalink
Optimize Write Signature calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
alanprot committed Apr 26, 2024
1 parent 55f996c commit c570fd3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
17 changes: 5 additions & 12 deletions pkg/cortexpb/extensions.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ var signerPool = sync.Pool{
}

type signer struct {
h *xxhash.Digest
b []byte
optimized bool
h *xxhash.Digest
b []byte
}

func newSigner() *signer {
Expand All @@ -38,29 +37,23 @@ func newSigner() *signer {
func (s *signer) Reset() {
s.h.Reset()
s.b = s.b[:0]
s.optimized = true
}

func (s *signer) WriteString(val string) {
switch {
case !s.optimized:
_, _ = s.h.WriteString(val)
case len(s.b)+len(val) > cap(s.b):
// If labels val does not fit in the []byte we fall back to not allocate the whole entry.
_, _ = s.h.Write(s.b)
_, _ = s.h.WriteString(val)
s.optimized = false
s.b = s.b[:0]
s.b = append(s.b, val...)
default:
// Use xxhash.Sum64(b) for fast path as it's faster.
s.b = append(s.b, val...)
}
}

func (s *signer) Sum64() uint64 {
if s.optimized {
return xxhash.Sum64(s.b)
}

_, _ = s.h.Write(s.b)
return s.h.Sum64()
}

Expand Down
26 changes: 26 additions & 0 deletions pkg/cortexpb/extensions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,32 @@ import (
"github.com/weaveworks/common/user"
)

func BenchmarkSignRequest(b *testing.B) {
ctx := context.Background()
ctx = user.InjectOrgID(ctx, "user-1")

tests := []struct {
size int
}{
{size: 10},
{size: 100},
{size: 1000},
{size: 10000},
}

for _, tc := range tests {
b.Run(fmt.Sprintf("WriteRequestSize: %v", tc.size), func(b *testing.B) {
wr := createWriteRequest(tc.size, true, "family1", "help1", "unit")
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, err := wr.Sign(ctx)
require.NoError(b, err)
}
})
}
}

func TestWriteRequest_Sign(t *testing.T) {
ctx := context.Background()
ctx = user.InjectOrgID(ctx, "user-1")
Expand Down

0 comments on commit c570fd3

Please sign in to comment.