Skip to content

Commit

Permalink
优化MultiBulkReply.ToBytes中内存分配的方式(提前分配);避免使用concatstrings和slicebytetos…
Browse files Browse the repository at this point in the history
…tring以提高性能;
  • Loading branch information
GongHongjun authored and HDT3213 committed Mar 26, 2024
1 parent b6763a8 commit 43c378c
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions redis/protocol/reply.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,34 @@ func MakeMultiBulkReply(args [][]byte) *MultiBulkReply {

// ToBytes marshal redis.Reply
func (r *MultiBulkReply) ToBytes() []byte {
argLen := len(r.Args)
var buf bytes.Buffer
buf.WriteString("*" + strconv.Itoa(argLen) + CRLF)
//Calculate the length of buffer
argLen := len(r.Args)
bufLen := 1 + len(strconv.Itoa(argLen)) + 2
for _, arg := range r.Args {
if arg == nil {
bufLen += 3 + 2
} else {
bufLen += 1 + len(strconv.Itoa(len(arg))) + 2 + len(arg) + 2
}
}
//Allocate memory
buf.Grow(bufLen)
//Write string step by step,avoid concat strings
buf.WriteString("*")
buf.WriteString(strconv.Itoa(argLen))
buf.WriteString(CRLF)
for _, arg := range r.Args {
if arg == nil {
buf.WriteString("$-1" + CRLF)
buf.WriteString("$-1")
buf.WriteString(CRLF)
} else {
buf.WriteString("$" + strconv.Itoa(len(arg)) + CRLF + string(arg) + CRLF)
buf.WriteString("$")
buf.WriteString(strconv.Itoa(len(arg)))
buf.WriteString(CRLF)
//Write bytes,avoid slice of byte to string(slicebytetostring)
buf.Write(arg)
buf.WriteString(CRLF)
}
}
return buf.Bytes()
Expand Down

0 comments on commit 43c378c

Please sign in to comment.