improve performance of random buffer usage for package grand

This commit is contained in:
John
2020-05-25 23:39:09 +08:00
parent b6ab1a992c
commit 8e6f1f1740
3 changed files with 32 additions and 9 deletions

View File

@ -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 {

View File

@ -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())
}

View File

@ -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]
}
}
}