https://github.com/kalloc/go-rand-bench
https://github.com/kalloc/go-rand-bench
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/kalloc/go-rand-bench
- Owner: kalloc
- Created: 2023-11-27T22:12:38.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2023-11-27T22:27:48.000Z (over 2 years ago)
- Last Synced: 2025-06-19T04:03:34.273Z (about 1 year ago)
- Language: Go
- Size: 3.91 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Code
```go
package main
import (
"math/rand"
"fmt"
)
func generateRandomString(length int) string {
const alphanum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const size = len(alphanum)
b := make([]byte, length)
for i := range b {
b[i] = alphanum[rand.Intn(size)]
}
return string(b)
}
func generateRandomString2(length int) string {
b := make([]byte, length)
rand.Read(b)
return fmt.Sprintf("%x", b)
}
func main() {
fmt.Println(generateRandomString(10))
fmt.Println(generateRandomString2(5))
}
```
## Output
```shell
SquVJQ5yYD
41100e791b
```
## Explanation
This is a small example showing how `fmt` can be expensive.
Please note that `math/rand` is not a good source for generating passwords and keys, use `crypto/rand` instead.
## Benchmark
```shell
go test -bench . -benchmem
```
```shell
goos: linux
goarch: amd64
pkg: example.com/m
cpu: Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz
BenchmarkGenerateRandomString-12 8636812 129.6 ns/op 16 B/op 1 allocs/op
BenchmarkGenerateRandomString2-12 8805774 146.9 ns/op 40 B/op 3 allocs/op
PASS
ok example.com/m 2.698s
```