Speeding Up Your Ruby on Rails App

Indexing, threading, compression, eager loading, lazy loading, pagination, Turbolinks and more.

Preface

First Thing’s First: The Database

Indexing: Why and When

class AddIndexToNameColumnOnPerson < ActiveRecord::Migration[5.2]
def change
add_index :people, :name
end
end
class AddPartialIndexToPersonOnCls < ActiveRecord::Migration[5.2]
def change
add_index :people, :cls, where: "(cls = hero)"
end
end

Pluck

Pagination: Don’t Use Kaminari (or Will Paginate)

Concurrency with Threading

Thread.new do
<code here>
end
def scrape_page(url)
Thread.new { Nokogiri::HTML(open(url)) }.value
end

Serializing: Ditch .to_json and AMS

Lazy-Loading Content

Eager Loading: Kill N+1 Queries

<% @people.each do | person | %>
<div> <%= person.house %> </div>
<% end %>
Person Load (40.7ms) SELECT "person".* FROM "people"House Load (0.8ms) SELECT "houses".* FROM "houses" WHERE "houses"."id" = ? LIMIT 1 [["id", 1]]
House Load (0.7ms) SELECT "houses".* FROM "houses" WHERE "houses"."id" = ? LIMIT 1 [["id", 3]]
House Load (0.7ms) SELECT "houses".* FROM "houses" WHERE "houses"."id" = ? LIMIT 1 [["id", 5]]
House Load...

Upgrade Ruby Itself

Don’t Ditch Turbolinks!

Compression (and minification)

Final Thoughts: Gems, jQuery, .count and Caching

Don’t Overuse Gems

jQuery

Use .size, not .count

Caching

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store