Skip to content

Commit

Permalink
preallocate tmparray to avoid allocation in loop (#132)
Browse files Browse the repository at this point in the history
Co-authored-by: Steve McDaniel <[email protected]>
Co-authored-by: Ashley Jeffs <[email protected]>
  • Loading branch information
3 people authored Feb 14, 2023
1 parent 08a5d6f commit d0749ab
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
17 changes: 11 additions & 6 deletions gabs.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,17 +155,22 @@ func (g *Container) searchStrict(allowWildcard bool, hierarchy ...string) (*Cont
}
case []interface{}:
if allowWildcard && pathSeg == "*" {
tmpArray := []interface{}{}
for _, val := range typedObj {
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 = typedObj
} else {
tmpArray = make([]interface{}, 0, len(typedObj))
for _, val := range typedObj {
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)
Expand Down
17 changes: 17 additions & 0 deletions gabs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1914,3 +1914,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"}...)
}
}

0 comments on commit d0749ab

Please sign in to comment.