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

feat: Add configurable size limit to recycled Parsers in pool #2

Merged
merged 3 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 30 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"math"
"strings"
"sync"
"testing"
"time"
)
Expand Down Expand Up @@ -188,6 +189,35 @@ func TestParserPool(t *testing.T) {
}
}

func TestParserPoolMaxSize(t *testing.T) {
var numNew, numNewLimit int
ppr := &ParserPool{
sync.Pool{New: func() interface{} { numNew++; return new(Parser) }},
}
pprLimit := &ParserPool{
sync.Pool{New: func() interface{} { numNewLimit++; return new(Parser) }},
}

parse := func(ppr *ParserPool, maxSize int, index int) {
var json = fmt.Sprintf(`{"%d":"test"}`, index)
pr := ppr.Get()
_, _ = pr.Parse(json)
ppr.PutIfSizeLessThan(pr, maxSize)
}
for i := 0; i < 10; i++ {
parse(ppr, 0, i)
parse(pprLimit, 1, i)
}

if numNew != 1 {
t.Fatalf("Expected exactly 1 calls to Pool New with no Max Size (not %d)", numNew)
}

if numNewLimit != 10 {
t.Fatalf("Expected exactly 10 calls to Pool with a Max Size (not %d)", numNewLimit)
}
}

func TestValueInvalidTypeConversion(t *testing.T) {
var p Parser

Expand Down
13 changes: 13 additions & 0 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,19 @@ func (pp *ParserPool) Put(p *Parser) {
pp.pool.Put(p)
}

// PutIfSizeLessThan PutIfLessThan Put returns p to pp only if the number of values in the cache is less than maxSize.
// If set to <= 0, no size limit is applied.
//
// p and objects recursively returned from p cannot be used after p is put into pp or released
func (pp *ParserPool) PutIfSizeLessThan(p *Parser, maxSize int) {
// Release the parser if the cache is too big
if maxSize > 0 && cap(p.c.vs) > maxSize {
return
}

pp.pool.Put(p)
}

// ArenaPool may be used for pooling Arenas for similarly typed JSONs.
type ArenaPool struct {
pool sync.Pool
Expand Down
Loading