Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ActiveRecordの速度改善Tips2020冬

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.
Avatar for patorash patorash
November 25, 2020

 ActiveRecordの速度改善Tips2020冬

Avatar for patorash

patorash

November 25, 2020
Tweet

More Decks by patorash

Other Decks in Programming

Transcript

  1. DBへのアクセス回数を減らすには? š パフォーマンス監視ツールを使う(rack-mini-profiler) š N+1問題の発生を検知するgemを使う(bullet) š counter_cacheを使う(Railsにある機能) š eager_load, preload,

    includes, left_joins, joinsなどのメソッドを使う š 大きいテーブルをjoinすると1回のクエリで済むが逆に性能が悪化するケースもあるので注意
  2. 大量のデータを取得しないようにするには? š find_each, find_in_batches, in_batchesなどのメソッドを使う š デフォルトで1,000件ずつ処理する š orderが効かないので注意 š

    ページングを行う(kaminari) š 存在チェックには、present?ではなく、exists?を使う š present?はモデルのオブジェクト作ってしまっているし、全部取得している š select * from ~ where ~ š exists?はクエリがシンプル š select 1 from ~ where ~
  3. 使うカラムのデータだけ取得するには? š selectメソッドで絞り込む š - articles.select(:id, :title).each do |article| =

    link_to article.title, article_path(article) end š pluckメソッドで値だけ取得する š - articles.pluck(:id, :title).each do |(id, title)| = link_to title, article_path(id) end