LoginSignup
0
0

More than 5 years have passed since last update.

railsのキャッシュの速度を計測してみた

Posted at

初めに

cacheについて調べて実際に計測してみた

参考記事
Railsのフラグメントキャッシュについて調べてみた
https://qiita.com/suketa/items/eeae7e2196520323f694

環境

userが1000件あってそれを読み込む

rails dev:cache

でcacheを有効にする。

users_controllerに

def index
  @users = User.all
end 

viewを

index.html.erb
    <h1>Users#index</h1>
    <p>Find me in app/views/users/index.html.erb</p>
    <% @users.each do |user| %>
            <%= user.first_name %>
            <%= user.last_name %>
            <%= user.phone %>
            <%= user.address %>
    <% end %>

これがキャッシュを使っていない普通の状態

実行してみると


Completed 200 OK in 198ms (Views: 173.6ms | ActiveRecord: 11.2ms)
Completed 200 OK in 48ms (Views: 41.7ms | ActiveRecord: 2.4ms)
Completed 200 OK in 51ms (Views: 45.0ms | ActiveRecord: 2.6ms)

最初は200ms位でそのあとは50ms位です

次にcacheを使ってみる

まずこんな感じのコードを書いてみた

index.html.erb

    <h1>Users#index</h1>
    <p>Find me in app/views/users/index.html.erb</p>
    <% @users.each do |user| %>
        <% cache user do %>
            <%= user.first_name %>
            <%= user.last_name %>
            <%= user.phone %>
            <%= user.address %>
        <% end %>
    <% end %>

結果はこんな感じ

Completed 200 OK in 993ms (Views: 976.4ms | ActiveRecord: 4.3ms)
Completed 200 OK in 364ms (Views: 343.8ms | ActiveRecord: 15.7ms)
Completed 200 OK in 393ms (Views: 386.7ms | ActiveRecord: 2.7ms)

時間はめっちゃ長くなった....

このキャッシュのやり方は調べたら結構出てきたやり方だけど使いどころは考えないといけないのかも…

とくに内容が特に無く数が多くなるものに関してはあんま良くないのかな?わかんないけど…

次にこのコード

users_controllerに

def index 
   @user_cache = User.last

   @users = User.all
end 

viewは

index.html.erb
<% cache(@user_cache) do  %>

    <h1>Users#index</h1>
    <p>Find me in app/views/users/index.html.erb</p>
    <% @users.each do |user| %>
            <%= user.first_name %>
            <%= user.last_name %>
            <%= user.phone %>
            <%= user.address %>
    <% end %>

<% end %>

これで結果は


Completed 200 OK in 214ms (Views: 197.8ms | ActiveRecord: 3.5ms)
Completed 200 OK in 32ms (Views: 28.2ms | ActiveRecord: 0.2ms)
Completed 200 OK in 34ms (Views: 29.5ms | ActiveRecord: 0.3ms)

初回は197msと遅いがそのあとは30ms以下と早くなった。

確かに二回目からの読み込みが少し早くなるけど正直cache使わないのとたいして変わらなかったのでまだあんまりcacheの良さがわからない…

多分使い方なんだろうけどとりあえずcache使えば良いってわけではなさそう

おわり:sunny:

0
0
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
0
0