In this article, I will show you tips to improve performance of Ruby on Rails application. let’s dive into those.
1. Limit Amount of Data in a Controller Method
Thin controllers are easy to test and has a good performance profile because there’s some overhead involved in passing the controller instance variable around. In short, you need to follow “Thin controller and fat model”.
2. Split View in Separate Partials
n this way, views will be easier to read and easier to cache.
3. Choose Right Session Storage
Based on your level of need, choose your session storage carefully. Here are what rails provide:
- CookieStore – Stores everything on the client.
- DRbStore – Stores the data on a DRb server.
- MemCacheStore – Stores the data in a memcache.
- ActiveRecordStore – Stores the data in a database using Active Record.
4. DRY (Don’t Repeat Yourself)
This is the most common things programmers tend to listen and don’t follow. Here is very basic example:
1 2 3 4 5
It should be written by:
4. Eager Loading
Eager loading is a way to solve the classic N + 1 query performance problem caused by inefficient use of child objects.
Let’s look at the following code. It will fetch zip of 10 users.
1 2 3 4 5
11 queries will be executed, 1 for the top and 10. The solution is to rewrite it to eager load address:
1 2 3 4 5
Database indexing is one of the simplest ways to improve database performance. The insert operation will become slower but will boost up fetching data which is more frequently used in web application.
6. Avoid Dynamism
Although find_by and find_all_by dynamic methods are really cool, the are also kind of slow because each one needs to run through method_missing and parse the filename against the list of columns in database table.
This is the purest way to speed up a rails application. Here are a short example of different types of caching:
- Page Caching
- Action Caching
- Fragment Caching
- SQL Caching
- Asset Caching
8. Image Spriting
In websites, a significant times are consumed for loading large number of images. One way of minimizing is to sprite your images. This will reduce number of images to be served significantly.
So far so good, these are pretty basic guidelines but surely help you to improve your application. Now, the bounce rate of your site should be less and you are expected to be a happier product owner. :)