Make cmd.String() faster

This commit is contained in:
Vladimir Mihailenco 2020-05-09 17:30:16 +03:00
parent 0557f66418
commit 3031343dae
2 changed files with 61 additions and 22 deletions

View File

@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"net" "net"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/go-redis/redis/v8/internal" "github.com/go-redis/redis/v8/internal"
@ -56,26 +55,6 @@ func writeCmd(wr *proto.Writer, cmd Cmder) error {
return wr.WriteArgs(cmd.Args()) return wr.WriteArgs(cmd.Args())
} }
func cmdString(cmd Cmder, val interface{}) string {
ss := make([]string, 0, len(cmd.Args()))
for _, arg := range cmd.Args() {
ss = append(ss, fmt.Sprint(arg))
}
s := strings.Join(ss, " ")
if err := cmd.Err(); err != nil {
return s + ": " + err.Error()
}
if val != nil {
switch vv := val.(type) {
case []byte:
return s + ": " + string(vv)
default:
return s + ": " + fmt.Sprint(val)
}
}
return s
}
func cmdFirstKeyPos(cmd Cmder, info *CommandInfo) int { func cmdFirstKeyPos(cmd Cmder, info *CommandInfo) int {
switch cmd.Name() { switch cmd.Name() {
case "eval", "evalsha": case "eval", "evalsha":
@ -93,6 +72,65 @@ func cmdFirstKeyPos(cmd Cmder, info *CommandInfo) int {
return int(info.FirstKeyPos) return int(info.FirstKeyPos)
} }
func cmdString(cmd Cmder, val interface{}) string {
b := make([]byte, 0, 32)
for i, arg := range cmd.Args() {
if i > 0 {
b = append(b, ' ')
}
b = appendArg(b, arg)
}
if err := cmd.Err(); err != nil {
b = append(b, ": "...)
b = append(b, err.Error()...)
} else if val != nil {
b = append(b, ": "...)
switch val := val.(type) {
case []byte:
b = append(b, val...)
default:
b = appendArg(b, val)
}
}
return string(b)
}
func appendArg(b []byte, v interface{}) []byte {
switch v := v.(type) {
case nil:
return append(b, "<nil>"...)
case string:
return append(b, v...)
case []byte:
return append(b, v...)
case int:
return strconv.AppendInt(b, int64(v), 10)
case int32:
return strconv.AppendInt(b, int64(v), 10)
case int64:
return strconv.AppendInt(b, v, 10)
case uint:
return strconv.AppendUint(b, uint64(v), 10)
case uint32:
return strconv.AppendUint(b, uint64(v), 10)
case uint64:
return strconv.AppendUint(b, v, 10)
case bool:
if v {
return append(b, "true"...)
}
return append(b, "false"...)
case time.Time:
return v.AppendFormat(b, time.RFC3339Nano)
default:
return append(b, fmt.Sprint(v)...)
}
}
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
type baseCmd struct { type baseCmd struct {

View File

@ -93,7 +93,8 @@ func (w *Writer) writeArg(v interface{}) error {
} }
return w.int(0) return w.int(0)
case time.Time: case time.Time:
return w.string(v.Format(time.RFC3339)) w.numBuf = v.AppendFormat(w.numBuf[:0], time.RFC3339Nano)
return w.bytes(w.numBuf)
case encoding.BinaryMarshaler: case encoding.BinaryMarshaler:
b, err := v.MarshalBinary() b, err := v.MarshalBinary()
if err != nil { if err != nil {