golang生成随机字符串

package random_string

import (
    "encoding/hex"
    "fmt"
    "math/rand"
    "testing"
    "time"
)

// 长度为62
var bytes []byte = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890")

func init() {
    // 保证每次生成的随机数不一样
    rand.Seed(time.Now().UnixNano())
}

// 方法一
func RandStr1(n int) string {
    result := make([]byte, n)
    for i := 0; i < n; i++ {
        result[i] = bytes[rand.Int31()%62]
    }
    return string(result)
}

// 方法二
func RandStr2(n int) string {
    result := make([]byte, n/2)
    rand.Read(result)
    return hex.EncodeToString(result)
}

// 对比一下两种方法的性能
func Benchmark1(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            RandStr1(12)
        }
    })
    // 结果:539.1 ns/op
}

func Benchmark2(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            RandStr2(12)
        }
    })
    // 结果: 157.2 ns/op
}

func TestOne(t *testing.T) {
    fmt.Println("方法一生成12位随机字符串: ", RandStr1(12))
    fmt.Println("方法二生成12位随机字符串: ", RandStr2(12))
}

~~~

posted on 2022-06-27 18:03  江湖乄夜雨  阅读(3172)  评论(0编辑  收藏  举报