Help us understand the problem. What is going on with this article?

Rails 日時フォーマットにI18nを使うときはレコード数に注意

[追記] 以下の内容ですが、違った可能性があります。ja.yamlの初回読み込みに時間がかかり、2回目以降はキャッシュが使われ早くなるという可能性があります(未検証)
[解決] 初回ロードに時間がかかるだけで、2回目以降は問題ありませんでした。I18nは便利なのでどんどん使っていきましょう

日付・日時のフォーマットにI18nを使用していたところ、処理時間がだいぶかかってしまいました。
そこで

  • I18n#l
  • Time#to_s
  • Time#strftime

の処理時間を調べてみました。
I18nに関してはこちら

測定

time = Time.now
sum_i18n = 0
sum_to_s = 0
sum_strftime = 0

# I18n#lの測定
100.times do
  s = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  I18n.l(time)
  e = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  sum_i18n += e-s
end

# Time#to_sの測定
100.times do
  s = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  time.to_s
  e = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  sum_to_s += e-s
end

# Time#strftimeの測定
100.times do
  s = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  time.strftime("%a %b %d %H:%M:%S %z %Y")
  e = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  sum_strftime += e-s
end

結果

I18n#l [s] Time#to_s [s] Time#strftime [s]
1回目 0.8247481999860611 0.002034699995419942 0.0011146999459015206
2回目 0.9185206999682123 0.0023584999435115606 0.0014091000193729997
3回目 0.8858548999996856 0.0011633000249275938 0.0014278999879024923

I18nは圧倒的に遅いですね。
レコード数が多い時はTime#strftimeを使った方が良さそうです。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした