google / uuid

Go package for UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
BSD 3-Clause "New" or "Revised" License
5.24k stars 363 forks source link

Add randomness pool mode for V4 UUID #80

Closed puzpuzpuz closed 3 years ago

puzpuzpuz commented 3 years ago

Adds an optional randomness pool mode for Random (Version 4) UUID generation. The pool contains random bytes read from the random number generator on demand in batches. Enabling the pool may improve the UUID generation throughput significantly.

Since the pool is stored on the Go heap, this feature may be a bad fit for security sensitive applications. That's why it's implemented as an opt-in feature.

Please treat this PR as a performance experiment.

Benchmarks

Environment: Ubuntu 20.04, go version go1.16.2 linux/amd64, i5-8300h

master branch:

BenchmarkUUID_New-8               597717            1797 ns/op        16 B/op          1 allocs/op

This branch:

BenchmarkUUID_New-8               632412            1809 ns/op        16 B/op          1 allocs/op
BenchmarkUUID_NewPooled-8        2058459           579.7 ns/op         0 B/op          0 allocs/op

The BenchmarkUUID_NewPooled benchmark here stands for the pool mode. The pool size could be increased from current 256 bytes to gain a slightly better throughput, but that would come at the cost of larger memory footprint.

puzpuzpuz commented 3 years ago

@pborman thanks for the review!

pierrre commented 3 years ago

Hi ! Just a quick question: why not use bufio.Reader ? Is it to heavy/complex ?

puzpuzpuz commented 3 years ago

why not use bufio.Reader ? Is it to heavy/complex ?

@pierrre TBH I didn't consider bufio.Reader when writing the code. The logic seems to be pretty straight-forward to me, so I kept the code simple and used a plain array + a position variable. But I guess, bufio.Reader would also work just fine.