From 739d2d9c80e0298dafb5df1c30bae35d63935d6c Mon Sep 17 00:00:00 2001 From: Name <1911860538@qq.com> Date: Tue, 5 Mar 2024 14:07:11 +0800 Subject: [PATCH] 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 --- context.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/context.go b/context.go index 420ff167..126d35db 100644 --- a/context.go +++ b/context.go @@ -113,20 +113,24 @@ func (c *Context) Copy() *Context { cp := Context{ writermem: c.writermem, Request: c.Request, - Params: c.Params, engine: c.engine, } + cp.writermem.ResponseWriter = nil cp.Writer = &cp.writermem cp.index = abortIndex 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 } - paramCopy := make([]Param, len(cp.Params)) - copy(paramCopy, cp.Params) - cp.Params = paramCopy + + cParams := c.Params + cp.Params = make([]Param, len(cParams)) + copy(cp.Params, cParams) + return &cp }