Skip to content

Commit 9b2f747

Browse files
committed
optimize the performance of the function appendFormatRFC3339
1 parent d68aec8 commit 9b2f747

File tree

2 files changed

+35
-8
lines changed

2 files changed

+35
-8
lines changed

src/time/format.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,33 @@ func appendInt(b []byte, x int, width int) []byte {
464464
return b
465465
}
466466

467+
const unitsDigit = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
468+
const tensDigit = "0000000000111111111122222222223333333333444444444455555555556666666666777777777788888888889999999999"
469+
470+
// appendIntWidth2 special scenario for appendInt, with parameter width=2
471+
func appendIntWidth2(b []byte, x int) []byte {
472+
if x < 0 {
473+
b = append(b, '-')
474+
x = -x
475+
}
476+
if x >= 1e2 {
477+
x %= 1e2
478+
}
479+
return append(b, tensDigit[x], unitsDigit[x])
480+
}
481+
482+
// appendIntWidth4 special scenario for appendInt, with parameter width=4
483+
func appendIntWidth4(b []byte, x int) []byte {
484+
if x < 0 {
485+
b = append(b, '-')
486+
x = -x
487+
}
488+
if x >= 1e4 {
489+
x %= 1e4
490+
}
491+
return append(b, tensDigit[x/1e2], unitsDigit[x/1e2], tensDigit[x%1e2], unitsDigit[x%1e2])
492+
}
493+
467494
// Never printed, just needs to be non-nil for return by atoi.
468495
var errAtoi = errors.New("time: invalid number")
469496

src/time/format_rfc3339.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,21 @@ func (t Time) appendFormatRFC3339(b []byte, nanos bool) []byte {
2020

2121
// Format date.
2222
year, month, day := abs.days().date()
23-
b = appendInt(b, year, 4)
23+
b = appendIntWidth4(b, year)
2424
b = append(b, '-')
25-
b = appendInt(b, int(month), 2)
25+
b = appendIntWidth2(b, int(month))
2626
b = append(b, '-')
27-
b = appendInt(b, day, 2)
27+
b = appendIntWidth2(b, day)
2828

2929
b = append(b, 'T')
3030

3131
// Format time.
3232
hour, min, sec := abs.clock()
33-
b = appendInt(b, hour, 2)
33+
b = appendIntWidth2(b, hour)
3434
b = append(b, ':')
35-
b = appendInt(b, min, 2)
35+
b = appendIntWidth2(b, min)
3636
b = append(b, ':')
37-
b = appendInt(b, sec, 2)
37+
b = appendIntWidth2(b, sec)
3838

3939
if nanos {
4040
std := stdFracSecond(stdFracSecond9, 9, '.')
@@ -53,9 +53,9 @@ func (t Time) appendFormatRFC3339(b []byte, nanos bool) []byte {
5353
} else {
5454
b = append(b, '+')
5555
}
56-
b = appendInt(b, zone/60, 2)
56+
b = appendIntWidth2(b, zone/60)
5757
b = append(b, ':')
58-
b = appendInt(b, zone%60, 2)
58+
b = appendIntWidth2(b, zone%60)
5959
return b
6060
}
6161

0 commit comments

Comments
 (0)