From 43c378cd4533e6dfc13e29d8145d78320506f3dd Mon Sep 17 00:00:00 2001 From: GongHongjun Date: Tue, 19 Mar 2024 12:39:08 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96MultiBulkReply.ToBytes?= =?UTF-8?q?=E4=B8=AD=E5=86=85=E5=AD=98=E5=88=86=E9=85=8D=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E5=BC=8F(=E6=8F=90=E5=89=8D=E5=88=86=E9=85=8D);=E9=81=BF?= =?UTF-8?q?=E5=85=8D=E4=BD=BF=E7=94=A8concatstrings=E5=92=8Cslicebytetostr?= =?UTF-8?q?ing=E4=BB=A5=E6=8F=90=E9=AB=98=E6=80=A7=E8=83=BD;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- redis/protocol/reply.go | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/redis/protocol/reply.go b/redis/protocol/reply.go index 98cadb1a..10bca09d 100644 --- a/redis/protocol/reply.go +++ b/redis/protocol/reply.go @@ -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()