Skip to content

Commit a7ea03f

Browse files
author
GuoHaoLan
committed
Optimize for buffer
1 parent fcb5d32 commit a7ea03f

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

main.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"os"
1717
"os/signal"
1818
"strconv"
19+
"sync"
1920
"syscall"
2021
"time"
2122

@@ -79,6 +80,15 @@ type Captcha struct {
7980
secret string
8081
}
8182

83+
var bufPool = sync.Pool{
84+
New: func() interface{} {
85+
// The Pool's New function should generally only return pointer
86+
// types, since a pointer can be put into the return interface
87+
// value without an allocation:
88+
return new(bytes.Buffer)
89+
},
90+
}
91+
8292
func (c *Captcha) CheckCaptchaIDExist(id string) bool {
8393
val, err := c.cache.Exists(ctx, id).Result()
8494

@@ -110,7 +120,7 @@ func (c *Captcha) GenCaptcha(w http.ResponseWriter, r *http.Request, _ httproute
110120
}
111121
id := uuid.NewString()
112122
d := captcha.RandomDigits(5)
113-
var buf bytes.Buffer
123+
114124
_image := &captcha.Image{}
115125
_cdata := CaptchaData{}
116126

@@ -128,11 +138,15 @@ func (c *Captcha) GenCaptcha(w http.ResponseWriter, r *http.Request, _ httproute
128138
_cdata.Width = 150
129139
_cdata.Height = 40
130140
}
141+
buf := bufPool.Get().(*bytes.Buffer)
142+
buf.Reset()
143+
defer bufPool.Put(buf)
131144

132-
if err := jpeg.Encode(&buf, _image.Paletted, nil); err != nil {
145+
if err := jpeg.Encode(buf, _image.Paletted, nil); err != nil {
133146
ThrowError(w, UNKNOWN_INNER_ERROR, err.Error())
134147
return
135148
}
149+
136150
_cdata.PhraseLen = 5
137151
_cdata.JpegBase64 = base64.StdEncoding.EncodeToString(buf.Bytes())
138152
ret := CaptchaRes{

0 commit comments

Comments
 (0)