golang高效生成UUIDv4字符串或字节的插件库fastuuid的使用
Golang高效生成UUIDv4字符串或字节的插件库fastuuid的使用
简介
fastuuid是一个高效的UUID库,目前仅实现了UUIDv4(基于加密随机数)生成器。它能在50-100纳秒内生成UUID字符串,仅需一次内存分配,并具有良好的CPU并行性能。
安装
go get github.com/rekby/fastuuid
使用示例
基本用法
package main
import (
"fmt"
"github.com/rekby/fastuuid"
)
func main() {
// 生成UUIDv4字符串
uuidStr := fastuuid.MustUUIDv4String()
fmt.Println("UUID string:", uuidStr)
// 生成UUIDv4字节数组
uuidBytes := fastuuid.MustUUIDv4Bytes()
fmt.Println("UUID bytes:", uuidBytes)
}
更完整的示例
package main
import (
"fmt"
"github.com/rekby/fastuuid"
)
func main() {
// 创建UUID生成器
generator := fastuuid.MustNewGenerator()
// 生成UUID字符串
uuid1 := generator.Hex128()
fmt.Println("Hex128 UUID:", uuid1)
// 生成另一种格式的UUID字符串
uuid2 := generator.String()
fmt.Println("String UUID:", uuid2)
// 生成UUID字节数组
uuidBytes := generator.Next()
fmt.Println("Raw bytes:", uuidBytes)
// 将字节数组转换为字符串
uuidFromBytes := fastuuid.UUIDBytesToString(uuidBytes)
fmt.Println("UUID from bytes:", uuidFromBytes)
}
性能基准测试
在Macbook Pro M1上的基准测试结果:
goos: darwin
goarch: arm64
pkg: github.com/rekby/fastuuid/benchmarks
BenchmarkRekbyUUID/one-thread 13688407 85.92 ns/op 48 B/op 1 allocs/op
BenchmarkRekbyUUID/multi-thread 25657815 51.81 ns/op 47 B/op 0 allocs/op
BenchmarkGoogleUUID4/one-thread 2256043 530.5 ns/op 64 B/op 2 allocs/op
BenchmarkGoogleUUID4/multi-thread 1897683 634.9 ns/op 63 B/op 1 allocs/op
可以看到fastuuid在单线程和多线程环境下都表现出优异的性能。
运行基准测试
如果你想自己运行基准测试:
git clone https://github.com/rekby/fastuuid.git
cd fastuuid/benchmarks
go test -test.bench=. -v
fastuuid是一个高效、简单的UUIDv4生成库,特别适合需要高性能生成UUID的场景。
更多关于golang高效生成UUIDv4字符串或字节的插件库fastuuid的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复