Skip to content

Commit 449b024

Browse files
authored
- eliminate 2 allocations in EachKey()
1 parent e015c37 commit 449b024

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

parser.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -370,20 +370,31 @@ func sameTree(p1, p2 []string) bool {
370370
return true
371371
}
372372

373+
const stackArraySize = 128
374+
373375
func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]string) int {
374376
var x struct{}
375-
pathFlags := make([]bool, len(paths))
376377
var level, pathsMatched, i int
377378
ln := len(data)
378379

380+
pathFlags := make([]bool, stackArraySize)[:]
381+
if len(paths) > cap(pathFlags) {
382+
pathFlags = make([]bool, len(paths))[:]
383+
}
384+
pathFlags = pathFlags[0:len(paths)]
385+
379386
var maxPath int
380387
for _, p := range paths {
381388
if len(p) > maxPath {
382389
maxPath = len(p)
383390
}
384391
}
385392

386-
pathsBuf := make([]string, maxPath)
393+
pathsBuf := make([]string, stackArraySize)[:]
394+
if maxPath > cap(pathsBuf) {
395+
pathsBuf = make([]string, maxPath)[:]
396+
}
397+
pathsBuf = pathsBuf[0:maxPath]
387398

388399
for i < ln {
389400
switch data[i] {
@@ -658,7 +669,6 @@ func calcAllocateSpace(keys []string, setValue []byte, comma, object bool) int {
658669
}
659670
}
660671

661-
662672
lk += len(setValue)
663673
for i := 1; i < len(keys); i++ {
664674
if string(keys[i][0]) == "[" {

0 commit comments

Comments
 (0)