lukeed / hexoid

A tiny (190B) and extremely fast utility to generate random IDs of fixed length

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

not fast nor small

telamon opened this issue · comments

Hey, stumbled upon this when I was looking for some docs/middleware that handles POST-payloads for polka.

Bro.. ur code.. it's.. I'm sorry 🤦‍♂️ a waste of string-ops and entropy...

If you want to minimize LOC have a oneliner:

export const hexoid = len => Array.from(new Array(len)).map(() => ((Math.random() * 0xff) | 0).toString(16)).join('')

If you want to target computational efficiency
Then don't throw away all the decimals it's, fresh entropy,
here's a variant that sweeps 8 letters (4bytes) per iteration,
it should be at least 8x faster.

export function hexoid (n = 16) {
  let s = ''
  for (;n>0; n-=8) s += ((0xffffffff * Math.random()) >>> 0).toString(16), s.length % 2 && (s+='0')
  return s.substr(0, s.length + n)
}
  • The LUT looks fun, not sure it's faster than toString(16)
  • Math.random() is collision-wise a horrible source of random..randomBytes(8).toString('hex') works nicer
  • Avoiding dynamic allocation speeds things up, when final size is known ahead of time, define your output array/string with set size and use it as working memory.

Thank you this was fun 🙏 can you point me in the right direction for parsing payload-data? I wanna go home 😢

i checked your suggestions and your supposedly 8x faster has even with more optimizations piss poor performance.

Validation (length = 16):
✔ hashids/fixed (example: "LkQWjnegYbwZ1p0G")
✔ nanoid/non-secure (example: "RxMWx_OWG3ZEU2IP")
✔ uid (example: "ab3uh4xtddczbg3f")
✔ hexoid (example: "291abaad0e45c700")
✔ telamon/16 (example: "491b78022158ae47")

Benchmark (length = 16):
hashids/fixed x 407,181 ops/sec ±0.63% (90 runs sampled)
nanoid/non-secure x 3,628,215 ops/sec ±0.38% (90 runs sampled)
uid x 3,156,761 ops/sec ±0.70% (92 runs sampled)
hexoid x 50,612,298 ops/sec ±0.96% (96 runs sampled)
telamon/16 x 1,019,537 ops/sec ±0.13% (96 runs sampled)