ulid icon indicating copy to clipboard operation
ulid copied to clipboard

Use rand.randbytes() instead of os.urandom()

Open socketpair opened this issue 1 year ago • 4 comments

[mmarkk@asus home]$ python -m timeit -s 'import random' 'random.randbytes(8)'
5000000 loops, best of 5: 93.9 nsec per loop
[mmarkk@asus home]$ python -m timeit -s 'import os' 'os.urandom(8)'
1000000 loops, best of 5: 248 nsec per loop

socketpair avatar Nov 02 '23 06:11 socketpair

randbytes is not cryptographically secure see https://docs.python.org/3/library/random.html#random.randbytes vs https://docs.python.org/3/library/os.html#os.urandom

Zaczero avatar Nov 12 '23 05:11 Zaczero

@Zaczero but ulid is not about security/cryptography, right ? But speed is important.

socketpair avatar Nov 12 '23 08:11 socketpair

Depends on the implementation, this specific one relies on cryptographically secure randomness: https://github.com/ahawker/ulid#components. ULID spec also recommends doing so: https://github.com/ulid/spec#components.

Zaczero avatar Nov 12 '23 11:11 Zaczero

If you don't care about unpredictability, maybe consider using the thread lock feature - https://github.com/ahawker/ulid#thread-lock - it removes the randomness for quick sequential id generations.

Zaczero avatar Nov 12 '23 11:11 Zaczero