4 ms·
I've gotten in the habit of using: SHA1(unix_timestamp + "misc salt phrase" + rand )[0, 8] It gives a nice, simple, 8 character id, pretty much not likely
by teej 17y ago
I've gotten in the habit of using:
SHA1(unix_timestamp + "misc salt phrase" + rand )[0, 8]
It gives a nice, simple, 8 character id, pretty much not likely to create a collision in a space of 1M keys, and not guessable. Am i doing it wrong?
- jhancock 17y agothis is just fine. you are only at risk if your db libs/frameworks have no checks for if collision does some day occur. For example, as an id being a primary key in a db table, your db will cough up an error if you get collision, but will your ruby/python/blub libs/frameworks handle it gracefully?
- CalmQuiet 17y agoIs it not a simple thing to require "unique" of the table column? ...and then if the occasional "error" occurs in attempt to create a new row in table have your framework retry until your randomizing routine succeeds in generating an unused ID? Or am I missing something?
- edw519 17y ago"pretty much not likely to create a collision" Depends on your definition of "pretty much not likely". It may be far more likely than you suspect. Remember that in a group of 30 people, there's a 50% chance 2 of them have the same birthday. Not exactly intuitive. Also remember that as your data base grows, the probability of collisions grows geometrically. Here's hoping that your app does so well that you'll need millions of IDs.
- teej 17y ago> Remember that in a group of 30 people, there's a 50% chance 2 of them have the same birthday. Not exactly intuitive. It's closer to 70%. You're very much correct, with my example, the chance of a collision is very, very high. I recalculated the odds, and by increasing the ID length to 12 (still a manageable size from a human readable standpoint), the odds of hitting a collision from 1M ids drops down to 0.1%. You can also just use sequences like someone mentioned earlier or seed your hash with something checked for uniqueness in advance, like a username. There seem to be plenty of ways of doing this right, just not my way!
- eli 17y agowhy not just timestamp + rand? (And make rand as many digits as needed to make it as long as you want)