Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest possible generated unique ID

So we can generate a unique id with str(uuid.uuid4()), which is 36 characters long.

Is there another method to generate a unique ID which is shorter in terms of characters?

EDIT:

  • If ID is usable as primary key then even better
  • Granularity should be better than 1ms
  • This code could be distributed, so we can't assume time independence.
like image 265
Roman Avatar asked Jul 13 '18 22:07

Roman


People also ask

Is there a shorter UUID?

1. NanoID is Only 108 bytes in Size. Unlike UUID, NanoID is 4.5 times smaller in size and does not have any dependencies.

How long should a unique ID be?

Universally Unique Identifiers, or UUIDS, are 128 bit numbers, composed of 16 octets and represented as 32 base-16 characters, that can be used to identify information across a computer system.

How do I get a random unique ID?

The randomly generated UUID uses a random number as the source to generate the UUID. In Java, the randomUUID() static method is used to generate a random UUID. The method internally uses SecureRandom class, which provides a cryptographically strong random number generator.


1 Answers

If this is for use as a primary key field in db, consider just using auto-incrementing integer instead.

str(uuid.uuid4()) is 36 chars but it has four useless dashes (-) in it, and it's limited to 0-9 a-f.

Better uuid4 in 32 chars:

>>> uuid.uuid4().hex
'b327fc1b6a2343e48af311343fc3f5a8'

Or just b64 encode and slice some urandom bytes (up to you to guarantee uniqueness):

>>> base64.b64encode(os.urandom(32))[:8]
b'iR4hZqs9'
like image 198
wim Avatar answered Oct 20 '22 13:10

wim