From 841adbf48d540ad053ac3dd5d5beed3babb63d17 Mon Sep 17 00:00:00 2001 From: Steve McDaniel Date: Sat, 14 Jan 2023 11:39:05 -0700 Subject: [PATCH 1/3] Pre-allocate array in Children() for mmap and add benchmark. --- gabs.go | 2 +- gabs_test.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/gabs.go b/gabs.go index 21d3371..07da9f7 100644 --- a/gabs.go +++ b/gabs.go @@ -255,7 +255,7 @@ func (g *Container) Children() []*Container { return children } if mmap, ok := g.Data().(map[string]interface{}); ok { - children := []*Container{} + children := make([]*Container, len(mmap)) for _, obj := range mmap { children = append(children, &Container{obj}) } diff --git a/gabs_test.go b/gabs_test.go index b005dba..6f246a7 100644 --- a/gabs_test.go +++ b/gabs_test.go @@ -1904,3 +1904,22 @@ func TestFlattenIncludeEmpty(t *testing.T) { } } } + +func BenchmarkChildren(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + jsonObj, err := ParseJSON(bigSample) + if err != nil { + b.Errorf("Error parsing json: %v\n", err) + } + + _ = jsonObj.Children() + + FOSI := jsonObj.S("firstOutter", "secondInner") + _ = FOSI.Children() + SOSI := jsonObj.S("secondOutter", "secondInner") + _ = SOSI.Children() + SOTI := jsonObj.S("secondOutter", "thirdInner") + _ = SOTI.Children() + } +} From 614b9eeb11e1d77b5cc4f207c3ae922c3a1d5e58 Mon Sep 17 00:00:00 2001 From: Steve McDaniel Date: Sat, 14 Jan 2023 11:58:17 -0700 Subject: [PATCH 2/3] Fixed an append issue noticed by Mihai --- gabs.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gabs.go b/gabs.go index 07da9f7..40d2f27 100644 --- a/gabs.go +++ b/gabs.go @@ -256,8 +256,10 @@ func (g *Container) Children() []*Container { } if mmap, ok := g.Data().(map[string]interface{}); ok { children := make([]*Container, len(mmap)) + i := 0 for _, obj := range mmap { - children = append(children, &Container{obj}) + children[i] = &Container{obj} + i++ } return children } From 1320df1435cf71af7dcee6ddb5ab244739dee3fd Mon Sep 17 00:00:00 2001 From: Steve McDaniel Date: Sat, 14 Jan 2023 12:06:45 -0700 Subject: [PATCH 3/3] use append instead of direct assignment, they are equivalent but the append is cleaner --- gabs.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/gabs.go b/gabs.go index 40d2f27..8792129 100644 --- a/gabs.go +++ b/gabs.go @@ -255,11 +255,9 @@ func (g *Container) Children() []*Container { return children } if mmap, ok := g.Data().(map[string]interface{}); ok { - children := make([]*Container, len(mmap)) - i := 0 + children := make([]*Container, 0, len(mmap)) for _, obj := range mmap { - children[i] = &Container{obj} - i++ + children = append(children, &Container{obj}) } return children }