Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

优化MultiBulkReply.ToBytes中内存分配的方式(提前分配);避免使用concatstrings和slicebytetos… #211

Merged
merged 1 commit into from
Mar 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading