Skip to content

Instantly share code, notes, and snippets.

@nguyentuan1696
Created March 10, 2023 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nguyentuan1696/4a0c93f1c3816226abd4fd90ebef27c2 to your computer and use it in GitHub Desktop.
Save nguyentuan1696/4a0c93f1c3816226abd4fd90ebef27c2 to your computer and use it in GitHub Desktop.
Random string best performance in Golang
// https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go
package main
import (
"fmt"
"math/rand"
"time"
"unsafe"
)
var src = rand.NewSource(time.Now().UnixNano())
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // 52 possibilities
letterIdxBits = 6 // 6 bits to represent 64 possibilities / indexes
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
func RandStringBytesMaskImprSrcUnsafe(n int) string {
b := make([]byte, n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}
func main() {
a := RandStringBytesMaskImprSrcUnsafe(6)
fmt.Print("a=", a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment