From: Zeke Lu Date: Tue, 4 Oct 2022 07:10:09 +0000 (+0000) Subject: reflect: avoid unnecessary copy of funcTypes X-Git-Tag: go1.20rc1~741 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=e7d203f494281a229a7d4ef769f14975e9b12e4e;p=gostls13.git reflect: avoid unnecessary copy of funcTypes Imagine that initFuncTypes is called with n=3, funcTypes will be [nil, nil, nil, **reflect.rtype] afterward, then it's called with n=2. The current implementation will copy funcTypes because funcTypes[2] is nil. This is unnecessary. It should make a new slice and copy funcTypes into it only when n >= len(funcTypes). Updates #56011. Change-Id: Ia093d2f550d6924a4c58bcd21325093e32b40baa GitHub-Last-Rev: a599eae7c2f6a388dfe1ff39cf61fd645885a64d GitHub-Pull-Request: golang/go#56024 Reviewed-on: https://go-review.googlesource.com/c/go/+/438395 Auto-Submit: Ian Lance Taylor Run-TryBot: Cuong Manh Le Reviewed-by: Ian Lance Taylor Reviewed-by: Keith Randall Run-TryBot: Ian Lance Taylor Auto-Submit: Keith Randall TryBot-Result: Gopher Robot Reviewed-by: Keith Randall --- diff --git a/src/reflect/type.go b/src/reflect/type.go index 339c982087..b06b7ffd9e 100644 --- a/src/reflect/type.go +++ b/src/reflect/type.go @@ -2005,13 +2005,15 @@ var funcTypesMutex sync.Mutex func initFuncTypes(n int) Type { funcTypesMutex.Lock() defer funcTypesMutex.Unlock() - if n < len(funcTypes) && funcTypes[n] != nil { + if n >= len(funcTypes) { + newFuncTypes := make([]Type, n+1) + copy(newFuncTypes, funcTypes) + funcTypes = newFuncTypes + } + if funcTypes[n] != nil { return funcTypes[n] } - newFuncTypes := make([]Type, n+1) - copy(newFuncTypes, funcTypes) - funcTypes = newFuncTypes funcTypes[n] = StructOf([]StructField{ { Name: "FuncType",