Skip to content

Commit 0357043

Browse files
committed
time: reduce allocs in Time.MarshalJSON and Time.MarshalText
Use non-exported constant error variables to save one allocation in unhappy path.
1 parent ef05b66 commit 0357043

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

src/time/format_rfc3339.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ func (t Time) appendFormatRFC3339(b []byte, nanos bool) []byte {
5959
return b
6060
}
6161

62+
var (
63+
errYearOutsideOfRange = errors.New("year outside of range [0,9999]")
64+
errTZHourOutsideOfRange = errors.New("timezone hour outside of range [0,23]")
65+
)
66+
6267
func (t Time) appendStrictRFC3339(b []byte) ([]byte, error) {
6368
n0 := len(b)
6469
b = t.appendFormatRFC3339(b, true)
@@ -69,11 +74,11 @@ func (t Time) appendStrictRFC3339(b []byte) ([]byte, error) {
6974
num2 := func(b []byte) byte { return 10*(b[0]-'0') + (b[1] - '0') }
7075
switch {
7176
case b[n0+len("9999")] != '-': // year must be exactly 4 digits wide
72-
return b, errors.New("year outside of range [0,9999]")
77+
return b, errYearOutsideOfRange
7378
case b[len(b)-1] != 'Z':
7479
c := b[len(b)-len("Z07:00")]
7580
if ('0' <= c && c <= '9') || num2(b[len(b)-len("07:00"):]) >= 24 {
76-
return b, errors.New("timezone hour outside of range [0,23]")
81+
return b, errTZHourOutsideOfRange
7782
}
7883
}
7984
return b, nil

0 commit comments

Comments
 (0)