Websites need to be fast, now more than ever before.
Google ranks fast websites higher, more people are using mobile devices to access their favorite sites and fast websites tend to sell better.
In this very brief article I'm going to show you 3 simple ways to improve your Rails 4 website speed. These tweaks are not difficult and you'll be surprised at the end results.
If you have tweaks of your, please feel free to share in the comments below!
This ensure your page content and stylesheets load first, and you display content on the page as soon as possible.
2. Use Include in your ActiveRecord queries.
.includes in your ActiveRecord query can save you some major cycles depending on the context.
Here's a simple example, taken directly from the official guides.
You're going to print out a list of
Client models. Each
Client has an associated
Address. You want to show a table like:
ID Name Age Address House # -------------------------------------------- 1 Sergio 23 Tonk St. 215
Many Rails developers suffer from this sort of performance drag. It's called
N+1 queries. Meaning, you're going to query something like,
select * from clients, then each time you want to display an address attribute related to that client you're going to execute yet another query! On larger data sets this is killer and will slow you down big time.
The fix is simple! (Read the title of this article!)
@clients = Client.all / In your view. - for client in @clients p= client.id p= client.name p= client.age p= client.address.street p= client.address.house_number
@clients = Client.all(include: :address) / In your view. - for client in @clients p= client.id p= client.name p= client.age p= client.address.street p= client.address.house_number
And voilá - you've managed to wrangle in a nasty bug that would have likely bitten you in the ass further down the line.
You can even drill down further and include parents of parents!
@expenses = Expense.all(:include => [:payment_type, [:supplier => :supplier_type]])
Unreadable, yes. Faster, also yes.
3. Use Bullet to warn you about inefficient queries.
There's a Gem out there called
Bullet. Basically what it does is nag you when you're writing bad code. Specifically inefficient ActiveRecord queries.
Installation is quite simple, just add in the gem to your
Gemfile and run the
bundle install command.
group :development do gem 'bullet' end bundle install
Then you need to set your Bullet configuration. This goes into your
# Bullet configuration to monitor and alert us of N+1 queries. config.after_initialize do Bullet.enable = true Bullet.alert = true Bullet.bullet_logger = false Bullet.console = false Bullet.growl = false Bullet.rails_logger = true Bullet.airbrake = false end
rails_logger option because I like seeing where the inefficiency was in the terminal while working on the controller code.
Know of a quick way to squeeze out those extra milliseconds? Share in the comments below!