go 性能优化
2022年1月19日
1 2 3 |
go test -bench=. -cpuprofile=cpu.prof //cpu性能报告 go test -bench=. -memprofile=mem.prof //内存性能报告 go tool pprof cpu.prof //输入命令后 进入操作面板, 输入: list processRequest 解释:list <方法名称> 查看每条代码用时 |
优化技巧, 使用 buf 连接字符串
json 不要用内置的, 用EasyJSON
优化案例 optmization.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package profiling import ( "encoding/json" "strconv" "strings" ) func createRequest() string { payload := make([]int, 100, 100) for i := 0; i < 100; i++ { payload[i] = i } req := Request{"demo_transaction", payload} v, err := json.Marshal(&req) if err != nil { panic(err) } return string(v) } /** * 优化后 */ func processRequest(reqs []string) []string { reps := []string{} for _, req := range reqs { reqObj := &Request{} /**这里使用了easyJson进行了性能优化开始*/ reqObj.UnmarshalJSON([]byte(req)) /**这里进行了性能优化开始*/ var buf strings.Builder for _, e := range reqObj.PayLoad { buf.WriteString(strconv.Itoa(e)) buf.WriteString(",") } repObj := &Response{reqObj.TransactionID, buf.String()} /**这里使用了easyJson进行了性能优化开始*/ repJson, err := repObj.MarshalJSON() if err != nil { panic(err) } reps = append(reps, string(repJson)) } return reps } /** * 优化前 */ func processRequestOld(reqs []string) []string { reps := []string{} for _, req := range reqs { reqObj := &Request{} json.Unmarshal([]byte(req), reqObj) ret := "" for _, e := range reqObj.PayLoad { ret += strconv.Itoa(e) + "," } repObj := &Response{reqObj.TransactionID, ret} repJson, err := json.Marshal(&repObj) if err != nil { panic(err) } reps = append(reps, string(repJson)) } return reps } |
结构文件 structs.go
1 2 3 4 5 6 7 8 9 10 11 |
package profiling type Request struct { TransactionID string `json:"transaction_id"` PayLoad []int `json:"payload"` } type Response struct { TransactionID string `json:"transaction_id"` Expression string `json:"exp"` } |
测试文件structs.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package profiling import "testing" /** * 测试优化后的代码 */ func BenchmarkProcessRequest(b *testing.B) { reqs := []string{} reqs = append(reqs, createRequest()) b.ResetTimer() for i := 0; i < b.N; i++ { _ = processRequest(reqs) } b.StopTimer() } /** * 测试优化前的代码 */ func BenchmarkProcessRequestOld(b *testing.B) { reqs := []string{} reqs = append(reqs, createRequest()) b.ResetTimer() for i := 0; i < b.N; i++ { _ = processRequestOld(reqs) } b.StopTimer() } |