Skip to content

encoding/json: reduce the number of allocations when decoding in streaming mode (Token API) #56307

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/encoding/json/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ type scanner struct {
// Reached end of top-level value.
endTop bool

// The scanner is used in streaming mode (i.e. by the Token API)
inStream bool

// Stack of what we're in the middle of - array values, object keys, object values.
parseState []int

Expand Down Expand Up @@ -280,6 +283,15 @@ func stateEndValue(s *scanner, c byte) int {
n := len(s.parseState)
if n == 0 {
// Completed top-level before the current byte.
if s.inStream {
// If used in streaming mode (i.e. by the Token API) do not allocate and set s.err in case the next
// character is non-space (which stateEndTop() would do). The error would be discarded anyway at the next
// call to readValue().
if s.err != nil {
return scanError
}
return scanEnd
}
s.step = stateEndTop
s.endTop = true
return stateEndTop(s, c)
Expand Down
5 changes: 5 additions & 0 deletions src/encoding/json/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,11 @@ func (d Delim) String() string {
// to mark the start and end of arrays and objects.
// Commas and colons are elided.
func (dec *Decoder) Token() (Token, error) {
dec.scan.inStream = true
defer func() {
dec.scan.inStream = false
}()

for {
c, err := dec.peek()
if err != nil {
Expand Down