3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

N+1問題の実験

Posted at

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
スクリーンショット 2018-10-24 23.36.47.png ### 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
スクリーンショット 2018-10-24 23.41.26.png ## Rendering: events/index 1164.4と書かれており、およそ処理が3倍以上になりました!

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

ではでは、、、

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?