github.com/nibnait/go-learn@v0.0.0-20220227013611-dfa47ea6d2da/src/test/chapter/ch9/01_optimize_eg/optimization.go (about)

     1  package profiling
     2  
     3  import (
     4  	"encoding/json"
     5  	"strconv"
     6  	"strings"
     7  )
     8  
     9  func createRequest() string {
    10  	payload := make([]int, 100, 100)
    11  	for i := 0; i < 100; i++ {
    12  		payload[i] = i
    13  	}
    14  	req := Request{"demo_transaction", payload}
    15  	v, err := json.Marshal(&req)
    16  	if err != nil {
    17  		panic(err)
    18  	}
    19  	return string(v)
    20  }
    21  
    22  func processRequest(reqs []string) []string {
    23  	reps := []string{}
    24  	for _, req := range reqs {
    25  		reqObj := &Request{}
    26  		reqObj.UnmarshalJSON([]byte(req))
    27  		//	01_json.Unmarshal([]byte(req), reqObj)
    28  
    29  		var buf strings.Builder
    30  		for _, e := range reqObj.PayLoad {
    31  			buf.WriteString(strconv.Itoa(e))
    32  			buf.WriteString(",")
    33  		}
    34  		repObj := &Response{reqObj.TransactionID, buf.String()}
    35  		repJson, err := repObj.MarshalJSON()
    36  		//repJson, err := 01_json.Marshal(&repObj)
    37  		if err != nil {
    38  			panic(err)
    39  		}
    40  		reps = append(reps, string(repJson))
    41  	}
    42  	return reps
    43  }
    44  
    45  func processRequestOld(reqs []string) []string {
    46  	reps := []string{}
    47  	for _, req := range reqs {
    48  		reqObj := &Request{}
    49  		json.Unmarshal([]byte(req), reqObj)
    50  		ret := ""
    51  		for _, e := range reqObj.PayLoad {
    52  			ret += strconv.Itoa(e) + ","
    53  		}
    54  		repObj := &Response{reqObj.TransactionID, ret}
    55  		repJson, err := json.Marshal(&repObj)
    56  		if err != nil {
    57  			panic(err)
    58  		}
    59  		reps = append(reps, string(repJson))
    60  	}
    61  	return reps
    62  }