LoginSignup
7
7

More than 5 years have passed since last update.

RubyでとりあえずサクッとID的なものを作成する

Posted at

ID的なもの

完全ではなくともとにかくIDとなるものが欲しいことはよくありますね。
というわけで、こういう条件で方法を探ってみました。

  • 作成された順番は分からなくていい
  • 処理が軽いといい(カリッカリにチューンするほどではないが)
  • 形式はそんなにこだわらない

時間測定

ものすごい適当に3つの方法を選んで、10000回実行した時の時間を測ってみました。

SecureRandom.uuid

こんな感じの文字列が取れます
6782f08f-534a-44f2-bce5-1b65d2fe340b

Benchmark.measure do
  10000.times{ SecureRandom.uuid }
end
=> #<Benchmark::Tms:0x007fe2349f4db8
 @cstime=0.0,
 @cutime=0.0,
 @label="",
 @real=0.074855,
 @stime=0.0,
 @total=0.07000000000000028,
 @utime=0.07000000000000028>

Digest::SHA1.hexdigest

こんな感じのIDが取れます
09b4f44552a6c7a879bbe59fde09b4c523c687cd

Benchmark.measure do
  10000.times{ Digest::SHA1.hexdigest([Time.now, rand].join) }
end
=> #<Benchmark::Tms:0x007fe23fab2fb0
 @cstime=0.0,
 @cutime=0.0,
 @label="",
 @real=0.08288,
 @stime=0.0,
 @total=0.08000000000000007,
 @utime=0.08000000000000007>

Identifier.generate

identifierというgemがあったので試してみました。

こんな感じのIDが取れます
00de7f79-b6c4-4507-8614-242a7bef930f

Benchmark.measure do
  10000.times{Identifier.generate}
end
=> #<Benchmark::Tms:0x007fe23d9e1e30
 @cstime=0.0,
 @cutime=0.0,
 @label="",
 @real=0.098369,
 @stime=0.009999999999999787,
 @total=0.10999999999999943,
 @utime=0.09999999999999964>

結果など

軽さは10000回でこのくらいならまあどれでもいいかな。
今回の目的からすると新たにgem入れることもないし、SecureRandom.uuidが楽なのでそれでいいかな。

調べてたらSecureRandom.uuidは中でSecureRandom.random_bytes叩いてるのを見てなるほどーってなったりしてました。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7