Skip to content

Commit d0749ab

Browse files
nibbleshiftJeffail
andauthored
preallocate tmparray to avoid allocation in loop (#132)
Co-authored-by: Steve McDaniel <nibbleshift@gmail.com> Co-authored-by: Ashley Jeffs <ash@jeffail.uk>
1 parent 08a5d6f commit d0749ab

2 files changed

Lines changed: 28 additions & 6 deletions

File tree

gabs.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -155,17 +155,22 @@ func (g *Container) searchStrict(allowWildcard bool, hierarchy ...string) (*Cont
155155
}
156156
case []interface{}:
157157
if allowWildcard && pathSeg == "*" {
158-
tmpArray := []interface{}{}
159-
for _, val := range typedObj {
160-
if (target + 1) >= len(hierarchy) {
161-
tmpArray = append(tmpArray, val)
162-
} else if res := Wrap(val).Search(hierarchy[target+1:]...); res != nil {
163-
tmpArray = append(tmpArray, res.Data())
158+
var tmpArray []interface{}
159+
if (target + 1) >= len(hierarchy) {
160+
tmpArray = typedObj
161+
} else {
162+
tmpArray = make([]interface{}, 0, len(typedObj))
163+
for _, val := range typedObj {
164+
if res := Wrap(val).Search(hierarchy[target+1:]...); res != nil {
165+
tmpArray = append(tmpArray, res.Data())
166+
}
164167
}
165168
}
169+
166170
if len(tmpArray) == 0 {
167171
return nil, nil
168172
}
173+
169174
return &Container{tmpArray}, nil
170175
}
171176
index, err := strconv.Atoi(pathSeg)

gabs_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1914,3 +1914,20 @@ func TestFlattenIncludeEmpty(t *testing.T) {
19141914
}
19151915
}
19161916
}
1917+
1918+
func BenchmarkWildcardSearch(b *testing.B) {
1919+
sample := []byte(`{"test":[{"value":10},{"value":20}]}`)
1920+
1921+
val, err := ParseJSON(sample)
1922+
if err != nil {
1923+
b.Fatalf("Failed to parse: %v", err)
1924+
}
1925+
1926+
b.ReportAllocs()
1927+
b.ResetTimer()
1928+
1929+
for i := 0; i < b.N; i++ {
1930+
val.Search([]string{"test", "*"}...)
1931+
val.Search([]string{"test", "*", "value"}...)
1932+
}
1933+
}

0 commit comments

Comments
 (0)