N+1問題の実験


include?メソッドを使ったN+1問題の実験をしてみましょう

今回はUserモデルがEventを投稿する
その投稿された一覧を取得する時間がinclude?メソッドの有無でどれほど違うか計測する
が今回の目標です。

必要なもの

1)seedを使ってイベントを1000件投稿させましょう

db/seed
1000.times do |index|
    Event.create(:eventname =>'実験サンプル', :when => '10/14 9:00',:where => 'ゴンザのパソコン',:user_id => '1',:text => 'N+1問題解決しよう!')
end

2)Gemfile rack-mini-profilerを使って処理速度を計測できるようにする

Gemfile
gem 'rack-mini-profiler', require: false

config/initializers/rack_mini_profiler.rbファイルを作成

config/initializers/rack_mini_profiler.rb
if Rails.env.development?
  require 'rack-mini-profiler'

  # initialization is skipped so trigger it
  Rack::MiniProfilerRails.initialize!(Rails.application)
end

これで準備は完了です

include?メソッドなしの場合

app/controller/event_controller.rb
class EventsController < ApplicationController
  #何もしない場合
  def index
   #投稿された全イベントを最新順に取得
   @events = Event.all.order("id DESC")
  end

Rendering: events/index 3744.9のとこを見ればわかりますが、3744.9ととてつもないですね

@events = Event.all.order("id DESC").includes(:user)

include?メソッドありだと?

app/controller/event_controller.rb
class EventsController < ApplicationController
  #include?メソッドありの場合
  def index
   #投稿された全イベントを最新順に取得
   @events = Event.all.order("id DESC").includes(:user)
  end

Rendering: events/index 1164.4と書かれており、およそ処理が3倍以上になりました!

投稿数が10000件を超えてinclude?なしで全データを取得など考えたらゾッとしますね笑
まだ他にも改善しなければいけないところはありますが、今回の実験でN+1問題を実感できました!

ではでは、、、