reflect: avoid unnecessary copy of funcTypes

Imagine that initFuncTypesthe 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).
This commit is contained in:
Zeke Lu 2022-10-04 14:17:35 +08:00
parent 6d8ec89303
commit a599eae7c2
1 changed files with 6 additions and 4 deletions

View File

@ -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",