Skip to content

Commit 54f8276

Browse files
authored
Merge pull request #49 from Basekick-Labs/perf/omitempty-two-pass
perf(encode): skip OmitEmpty slice allocation when no fields omitted
2 parents 2382197 + daaca16 commit 54f8276

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

types.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,20 @@ func (fs *fields) OmitEmpty(e *Encoder, strct reflect.Value) []*field {
159159
return fs.List
160160
}
161161

162-
fields := make([]*field, 0, len(fs.List))
162+
// First pass: count surviving fields. If all survive, return the
163+
// original slice without allocating a filtered copy.
164+
n := 0
165+
for _, f := range fs.List {
166+
if !f.Omit(e, strct) {
167+
n++
168+
}
169+
}
170+
if n == len(fs.List) {
171+
return fs.List
172+
}
163173

174+
// Second pass: build the filtered slice only when necessary.
175+
fields := make([]*field, 0, n)
164176
for _, f := range fs.List {
165177
if !f.Omit(e, strct) {
166178
fields = append(fields, f)

0 commit comments

Comments
 (0)