Skip to content

Commit 1403f74

Browse files
okhowangweijunyi
authored andcommitted
perf: reuse zlib.Writer
before: BenchmarkGenSig BenchmarkGenSig-16 7788 150884 ns/op 817750 B/op 62 allocs/op BenchmarkGenUserSigWithBuf BenchmarkGenUserSigWithBuf-16 7298 140476 ns/op 818145 B/op 68 allocs/op after: BenchmarkGenSig BenchmarkGenSig-16 39601 30510 ns/op 3896 B/op 42 allocs/op BenchmarkGenUserSigWithBuf BenchmarkGenUserSigWithBuf-16 38188 31464 ns/op 4064 B/op 48 allocs/op
1 parent 515f281 commit 1403f74

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

tencentyun/TLSSigAPI.go

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@ import (
88
"encoding/base64"
99
"encoding/json"
1010
"errors"
11+
"io"
1112
"io/ioutil"
1213
"strconv"
14+
"sync"
1315
"time"
1416
)
1517

@@ -23,7 +25,7 @@ import (
2325
* expire - UserSig 票据的过期时间,单位是秒,比如 86400 代表生成的 UserSig 票据在一天后就无法再使用了。
2426
*/
2527

26-
/**
28+
/**
2729
* Function: Used to issue UserSig that is required by the TRTC and IM services.
2830
*
2931
* Parameter description:
@@ -94,7 +96,6 @@ func GenUserSigWithBuf(sdkappid int, key string, userid string, expire int, buf
9496
* - privilegeMap == 0010 1010 == 42: Indicates that the UserID has only the permissions to enter the room and receive audio/video data.
9597
*/
9698

97-
9899
func GenPrivateMapKey(sdkappid int, key string, userid string, expire int, roomid uint32, privilegeMap uint32) (string, error) {
99100
var userbuf []byte = genUserBuf(userid, sdkappid, roomid, expire, privilegeMap, 0, "")
100101
return genSig(sdkappid, key, userid, expire, userbuf)
@@ -290,7 +291,8 @@ func genSig(sdkappid int, key string, identifier string, expire int, userbuf []b
290291
}
291292

292293
var b bytes.Buffer
293-
w := zlib.NewWriter(&b)
294+
w := newZlibWriter(&b)
295+
defer zlibWriterPool.Put(w)
294296
if _, err = w.Write(data); err != nil {
295297
return "", err
296298
}
@@ -413,3 +415,17 @@ var (
413415
ErrUserBufNotMatch = errors.New("userbuf not match")
414416
ErrSigNotMatch = errors.New("sig not match")
415417
)
418+
419+
var (
420+
zlibWriterPool sync.Pool
421+
)
422+
423+
func newZlibWriter(w io.Writer) *zlib.Writer {
424+
v := zlibWriterPool.Get()
425+
if v == nil {
426+
return zlib.NewWriter(w)
427+
}
428+
zw := v.(*zlib.Writer)
429+
zw.Reset(w)
430+
return zw
431+
}

0 commit comments

Comments
 (0)