Skip to content
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

encoding/json: optimize field sorting with slices and cmp #67046

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 12 additions & 10 deletions src/encoding/json/encode.go
Expand Up @@ -12,13 +12,13 @@ package json

import (
"bytes"
"cmp"
"encoding"
"encoding/base64"
"fmt"
"math"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -1162,21 +1162,23 @@ func typeFields(t reflect.Type) structFields {
}
}

sort.Slice(fields, func(i, j int) bool {
x := fields
slices.SortFunc(fields, func(a, b field) int {
// sort field by name, breaking ties with depth, then
// breaking ties with "name came from json tag", then
// breaking ties with index sequence.
if x[i].name != x[j].name {
return x[i].name < x[j].name
if c := strings.Compare(a.name, b.name); c != 0 {
return c
}
if len(x[i].index) != len(x[j].index) {
return len(x[i].index) < len(x[j].index)
if c := cmp.Compare(len(a.index), len(b.index)); c != 0 {
return c
}
if x[i].tag != x[j].tag {
return x[i].tag
if a.tag != b.tag {
if a.tag {
return -1
}
return +1
}
return slices.Compare(x[i].index, x[j].index) == -1
return slices.Compare(a.index, b.index)
})

// Delete all fields that are hidden by the Go rules for embedded fields,
Expand Down