]> Cypherpunks.ru repositories - gostls13.git/commitdiff
reflect: avoid unnecessary copy of funcTypes
authorZeke Lu <lvzecai@gmail.com>
Tue, 4 Oct 2022 07:10:09 +0000 (07:10 +0000)
committerGopher Robot <gobot@golang.org>
Tue, 4 Oct 2022 23:15:54 +0000 (23:15 +0000)
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 <iant@google.com>
Run-TryBot: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Keith Randall <khr@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Auto-Submit: Keith Randall <khr@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Keith Randall <khr@golang.org>
src/reflect/type.go

index 339c982087afa060173080ee5b1b1f27b2f9e81e..b06b7ffd9e2d6f3fb9535091bbfe8442e1120c04 100644 (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",