chore(perf): Optimize the Copy method of the Context struct (#3859)

* Optimize the Copy method of the Context struct: using 'make' to initialize the map('cp.Keys') with a length of 'c.Keys'; avoiding repeatedly assiging the 'params' to 'context'.

* Using temporary variables to save c.Keys and c.Params to prevent them from changing during the copying process.

---------

Co-authored-by: huangzw <huangzw@hsmap.com>
This commit is contained in:
Name 2024-03-05 14:07:11 +08:00 committed by GitHub
parent ecdbbbe948
commit 739d2d9c80
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -113,20 +113,24 @@ func (c *Context) Copy() *Context {
cp := Context{ cp := Context{
writermem: c.writermem, writermem: c.writermem,
Request: c.Request, Request: c.Request,
Params: c.Params,
engine: c.engine, engine: c.engine,
} }
cp.writermem.ResponseWriter = nil cp.writermem.ResponseWriter = nil
cp.Writer = &cp.writermem cp.Writer = &cp.writermem
cp.index = abortIndex cp.index = abortIndex
cp.handlers = nil cp.handlers = nil
cp.Keys = map[string]any{}
for k, v := range c.Keys { cKeys := c.Keys
cp.Keys = make(map[string]any, len(cKeys))
for k, v := range cKeys {
cp.Keys[k] = v cp.Keys[k] = v
} }
paramCopy := make([]Param, len(cp.Params))
copy(paramCopy, cp.Params) cParams := c.Params
cp.Params = paramCopy cp.Params = make([]Param, len(cParams))
copy(cp.Params, cParams)
return &cp return &cp
} }