Skip to content

Commit

Permalink
ValidCharacters.sanitizeFn: Pool buffers (#177)
Browse files Browse the repository at this point in the history
  • Loading branch information
abhinav authored Jun 17, 2022
1 parent b9d82b0 commit b1da0cc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
22 changes: 20 additions & 2 deletions sanitize.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package tally

import (
"bytes"
"sync"
)

var (
Expand Down Expand Up @@ -124,6 +125,21 @@ func (s sanitizer) Value(v string) string {
return s.valueFn(v)
}

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

func getSanitizeBuffer() *bytes.Buffer {
return _sanitizeBuffers.Get().(*bytes.Buffer)
}

func putSanitizeBuffer(b *bytes.Buffer) {
b.Reset()
_sanitizeBuffers.Put(b)
}

func (c *ValidCharacters) sanitizeFn(repChar rune) SanitizeFn {
return func(value string) string {
var buf *bytes.Buffer
Expand Down Expand Up @@ -155,7 +171,7 @@ func (c *ValidCharacters) sanitizeFn(repChar rune) SanitizeFn {
// ie the character is invalid, and the buffer has not been initialised
// so we initialise buffer and backfill
if buf == nil {
buf = bytes.NewBuffer(make([]byte, 0, len(value)))
buf = getSanitizeBuffer()
if idx > 0 {
buf.WriteString(value[:idx])
}
Expand All @@ -171,6 +187,8 @@ func (c *ValidCharacters) sanitizeFn(repChar rune) SanitizeFn {
}

// otherwise, return the newly constructed buffer
return buf.String()
result := buf.String()
putSanitizeBuffer(buf)
return result
}
}
8 changes: 8 additions & 0 deletions sanitize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,11 @@ func TestSanitizeTestCases(t *testing.T) {
require.Equal(t, tc.output, fn(tc.input))
}
}

func BenchmarkSanitizeFn(b *testing.B) {
sanitize := newTestSanitizer()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = sanitize("foo bar")
}
}

0 comments on commit b1da0cc

Please sign in to comment.