Best Practices for Ruby on Rails application
Optimizing Performance of Rails app
hey folks!
After binging several articles, and videos and optimizing my rails code. I thought why not share this newly profound knowledge?
And of course, generosity doesn’t require general’s order .so let’s get into it.
Scaling your server for application is always not a solution nor the reason for slowing down your application. Ruby on Rails is such a great framework if you know the right way.
let's talk about some database query optimization first!
N+1 query and performance optimization
The first thing you can do to optimize your app is to kill N+1 queries. Basically, if you are hitting your database more times than you need to. If you are grabbing n table entries n+1 times.
bundle add bulletbundle installrails g bullet: install
After you install it in your app and start visiting various routes in development. It will show alert boxes with warnings indicating database queries that need to be optimized.
make sure you add bullet gem to only the dev group as you don't get surprised by alert boxes after deployment.
Rack-mini-profiler :
This is a popular gem used for monitoring how long it took for the request to be processed and how much of that time it was doing various rendering, and database queries.
you can start by adding
gem 'rack-mini-profiler'
to your gem file and running the bundle and starting your application.
you would be able to see something like this in corner of your browser.
if you click this you’ll see a window open with this speed analysis.
Counter Caches
There is a lot of discussion about what to use for counting the number of records in rails. should we use .length or is it better to use .count and how does .size be different from these two? and the answer to this question is ‘it depends.
but you know what's even better and simple? to use a counter cache.
for implementing counter cache we simply add an integer column and let the associate model know that it has to update it whenever data gets added to the table or destroyed from the table.
These are some of the ways I found useful! feel free to add your best practices !
Happy coding!
References