Skip to content

Commit

Permalink
Only convert to any on KindAny values (#83)
Browse files Browse the repository at this point in the history
* Only convert to any on KindAny values

Indiscriminately calling slog.Value.Any() on the value causes extra allocations for non-any values. Benchmark shows that for each string attribute, an extra 16-byte allocation is incurred.

This commit adds a check so Any() is only called on values of KindAny.

* drop comment

---------

Co-authored-by: lmittmann <[email protected]>
  • Loading branch information
database64128 and lmittmann authored Dec 10, 2024
1 parent 7c923ea commit e3abebc
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,23 +353,27 @@ func (h *handler) appendAttr(buf *buffer, attr slog.Attr, groupsPrefix string, g
return
}

if attr.Value.Kind() == slog.KindGroup {
switch attr.Value.Kind() {
case slog.KindAny:
if err, ok := attr.Value.Any().(tintError); ok {
h.appendTintError(buf, err, attr.Key, groupsPrefix)
buf.WriteByte(' ')
return
}
case slog.KindGroup:
if attr.Key != "" {
groupsPrefix += attr.Key + "."
groups = append(groups, attr.Key)
}
for _, groupAttr := range attr.Value.Group() {
h.appendAttr(buf, groupAttr, groupsPrefix, groups)
}
} else if err, ok := attr.Value.Any().(tintError); ok {
// append tintError
h.appendTintError(buf, err, attr.Key, groupsPrefix)
buf.WriteByte(' ')
} else {
h.appendKey(buf, attr.Key, groupsPrefix)
h.appendValue(buf, attr.Value, true)
buf.WriteByte(' ')
return
}

h.appendKey(buf, attr.Key, groupsPrefix)
h.appendValue(buf, attr.Value, true)
buf.WriteByte(' ')
}

func (h *handler) appendKey(buf *buffer, key, groups string) {
Expand Down

0 comments on commit e3abebc

Please sign in to comment.