]> Cypherpunks repositories - gostls13.git/commitdiff
go/token: allocate fewer times at init time
authorDaniel Martí <mvdan@mvdan.cc>
Wed, 9 Mar 2022 14:57:58 +0000 (14:57 +0000)
committerDaniel Martí <mvdan@mvdan.cc>
Thu, 10 Mar 2022 09:12:04 +0000 (09:12 +0000)
go/token has had a global "keywords" map filled at init time for years.
Overall, the package's init time cost is small, as per GODEBUG=inittrace=1:

init go/token @0.51 ms, 0.004 ms clock, 1776 bytes, 5 allocs
init go/token @0.44 ms, 0.003 ms clock, 1776 bytes, 5 allocs
init go/token @0.45 ms, 0.003 ms clock, 1568 bytes, 4 allocs

However, adding the map size hint does help with the allocations:

init go/token @0.45 ms, 0.002 ms clock, 944 bytes, 2 allocs
init go/token @0.46 ms, 0.002 ms clock, 944 bytes, 2 allocs
init go/token @0.55 ms, 0.003 ms clock, 1152 bytes, 3 allocs

Three samples are rather unscientific, and the clock time is basically
unchanged, but we might as well reduce the allocs.

Change-Id: I48121a4cea4113d991882e32f274d7b7736800dc
Reviewed-on: https://go-review.googlesource.com/c/go/+/391094
Trust: Daniel Martí <mvdan@mvdan.cc>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>

src/go/token/token.go

index dd0f4f82345ef8ee4eac0b74d637ff1c01726fd4..17047d87138d61bd5b55249e299d69459182b44b 100644 (file)
@@ -286,7 +286,7 @@ func (op Token) Precedence() int {
 var keywords map[string]Token
 
 func init() {
-       keywords = make(map[string]Token)
+       keywords = make(map[string]Token, keyword_end-(keyword_beg+1))
        for i := keyword_beg + 1; i < keyword_end; i++ {
                keywords[tokens[i]] = i
        }