From 8e6f1f1740ee9f7c8e3832bc2340a099e88b05bd Mon Sep 17 00:00:00 2001 From: John Date: Mon, 25 May 2020 23:39:09 +0800 Subject: [PATCH] improve performance of random buffer usage for package grand --- .example/other/test.go | 10 ++++++++++ .example/util/guid/guid.go | 5 +---- util/grand/grand_buffer.go | 26 +++++++++++++++++++++----- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/.example/other/test.go b/.example/other/test.go index 233938c85..f6e15be50 100644 --- a/.example/other/test.go +++ b/.example/other/test.go @@ -3,8 +3,18 @@ package main import ( "fmt" "github.com/gogf/gf/encoding/gjson" + "github.com/gogf/gf/net/ghttp" + "github.com/gogf/gf/util/guid" ) +func CreateSessionId(r *ghttp.Request) string { + var ( + agent = r.UserAgent() + address = r.RemoteAddr + cookie = r.Header.Get("Cookie") + ) + return guid.S([]byte(agent), []byte(address), []byte(cookie)) +} func main() { body := "{\"id\": 413231383385427875}" if dat, err := gjson.DecodeToJson(body); err == nil { diff --git a/.example/util/guid/guid.go b/.example/util/guid/guid.go index 39bbdc6b3..439cf9869 100644 --- a/.example/util/guid/guid.go +++ b/.example/util/guid/guid.go @@ -6,8 +6,5 @@ import ( ) func main() { - for i := 0; i < 1000; i++ { - s := guid.S() - fmt.Println(s, len(s)) - } + fmt.Printf("TraceId: %s\n", guid.S()) } diff --git a/util/grand/grand_buffer.go b/util/grand/grand_buffer.go index 95c658444..d83801edb 100644 --- a/util/grand/grand_buffer.go +++ b/util/grand/grand_buffer.go @@ -29,15 +29,31 @@ func init() { // to produce the random bytes, and a buffer chan to store the random bytes. // So it has high performance to generate random numbers. func asyncProducingRandomBufferBytesLoop() { - buffer := make([]byte, 1024) + var step int for { + buffer := make([]byte, 1024) if n, err := rand.Read(buffer); err != nil { panic(err) } else { - for i := 0; i < n-4; i += 4 { - b := make([]byte, 4) - copy(b, buffer[i:i+4]) - bufferChan <- b + // The random buffer from system is very expensive, + // so fully reuse the random buffer by changing + // the step with a different prime number can + // improve the performance a lot. + step = 4 + for i := 0; i < n-4; i += step { + bufferChan <- buffer[i : i+4] + } + step = 5 + for i := 0; i < n-4; i += step { + bufferChan <- buffer[i : i+4] + } + step = 7 + for i := 0; i < n-4; i += step { + bufferChan <- buffer[i : i+4] + } + step = 13 + for i := 0; i < n-4; i += step { + bufferChan <- buffer[i : i+4] } } }