有了优化版的 Replace 函数就替换到项目中吧:
// 第一部分 func (v2 *v2Adapter) parse(s string) (*AdRequest, error) { b := exbytes.Replace(exstrings.UnsafeToBytes(s), []byte(" "), []byte(""), -1) requestJSON, err := v2.paramCrypto.Decrypt(b) if err != nil { return nil, err } request := v2.getDefaultAdRequest() if err := request.UnmarshalJSON(requestJSON); err != nil { return nil, err } return request, nil } // 第二部分 func (v3 *v3Adapter) parseEncrypt(s []byte) ([]byte, error) { s = exbytes.Replace(s, []byte(" "), []byte(""), -1) requestJSON, err := v3.paramCrypto.Decrypt(s) if err != nil { return nil, err } return requestJSON, nil } // 第三部分 type LogItems []string func LogItemsToBytes(items []string, sep, newline string) []byte { for i := range items { items[i] = exbytes.ToString(exbytes.Replace(exstrings.UnsafeToBytes(items[i]), []byte(sep), []byte(" "), -1)) } b := exbytes.Replace(exstrings.UnsafeToBytes(strings.Join(items, sep)), []byte(newline), []byte(" "), -1) return append(b, newline...) } 上线后性能分析 $ go tool pprof allocs2 File: xx Type: alloc_space Time: Feb 2, 2019 at 5:33pm (CST) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top exbytes.Replace Focus expression matched no samples Active filters: focus=exbytes.Replace Showing nodes accounting for 0, 0% of 864.21GB total flat flat% sum% cum cum% (pprof)居然在 allocs 上居然找不到了,确实是零分配。
优化前 profile :
$ go tool pprof profile File: xx Type: cpu Time: Feb 1, 2019 at 9:54pm (CST) Duration: 30.08s, Total samples = 12.23s (40.65%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top strings.Replace Active filters: focus=strings.Replace Showing nodes accounting for 0.08s, 0.65% of 12.23s total Showing top 10 nodes out of 27 flat flat% sum% cum cum% 0.03s 0.25% 0.25% 0.08s 0.65% strings.Replace 0.02s 0.16% 0.41% 0.02s 0.16% countbody 0.01s 0.082% 0.49% 0.01s 0.082% indexbytebody 0.01s 0.082% 0.57% 0.01s 0.082% memeqbody 0.01s 0.082% 0.65% 0.01s 0.082% runtime.scanobject优化后 profile :
$ go tool pprof profile2 File: xx Type: cpu Time: Feb 2, 2019 at 5:33pm (CST) Duration: 30.16s, Total samples = 14.68s (48.68%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top exbytes.Replace Active filters: focus=exbytes.Replace Showing nodes accounting for 0.06s, 0.41% of 14.68s total Showing top 10 nodes out of 18 flat flat% sum% cum cum% 0.03s 0.2% 0.2% 0.03s 0.2% indexbytebody 0.02s 0.14% 0.34% 0.05s 0.34% bytes.Index 0.01s 0.068% 0.41% 0.06s 0.41% github.com/thinkeridea/go-extend/exbytes.Replace通过 profile 来分配发现性能也有一定的提升,本次 strings.Replace 和 bytes.Replace 优化圆满结束。
本博文中使用函数均在 go-extend 中,优化后的函数在 exbytes.Replace 中。