From 080cd39786a74fdea6bcd3f168a7f82d8fc18154 Mon Sep 17 00:00:00 2001 From: Steve McDaniel Date: Sat, 14 Jan 2023 11:19:05 -0700 Subject: [PATCH] preallocate tmparray to avoid allocation in loop --- gabs.go | 17 +++++++++++------ gabs_test.go | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/gabs.go b/gabs.go index 21d3371..50f9fd3 100644 --- a/gabs.go +++ b/gabs.go @@ -148,17 +148,22 @@ func (g *Container) searchStrict(allowWildcard bool, hierarchy ...string) (*Cont } } else if marray, ok := object.([]interface{}); ok { if allowWildcard && pathSeg == "*" { - tmpArray := []interface{}{} - for _, val := range marray { - if (target + 1) >= len(hierarchy) { - tmpArray = append(tmpArray, val) - } else if res := Wrap(val).Search(hierarchy[target+1:]...); res != nil { - tmpArray = append(tmpArray, res.Data()) + var tmpArray []interface{} + if (target + 1) >= len(hierarchy) { + tmpArray = marray + } else { + tmpArray = make([]interface{}, 0, len(marray)) + for _, val := range marray { + if res := Wrap(val).Search(hierarchy[target+1:]...); res != nil { + tmpArray = append(tmpArray, res.Data()) + } } } + if len(tmpArray) == 0 { return nil, nil } + return &Container{tmpArray}, nil } index, err := strconv.Atoi(pathSeg) diff --git a/gabs_test.go b/gabs_test.go index b005dba..726c23d 100644 --- a/gabs_test.go +++ b/gabs_test.go @@ -1904,3 +1904,20 @@ func TestFlattenIncludeEmpty(t *testing.T) { } } } + +func BenchmarkWildcardSearch(b *testing.B) { + sample := []byte(`{"test":[{"value":10},{"value":20}]}`) + + val, err := ParseJSON(sample) + if err != nil { + b.Fatalf("Failed to parse: %v", err) + } + + b.ReportAllocs() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + val.Search([]string{"test", "*"}...) + val.Search([]string{"test", "*", "value"}...) + } +}