We’re continuing our new regular screencasts series on Syndicode’s YouTube channel! As we are Ruby on Rails agency, we’d like to deliver some great Ruby lifehacks to you and hope you will find it useful! Prepared by Paul Leoniuk, Rails lifehacks will bring you some interesting and useful knowledge. If you will have any comments, questions or suggestions, leave your comments under the post or under the original video on our YouTube channel. Today we’ll tell you about big database queries and highload optimization!
Today we are talking about optimization, big databases queries and how to make your application stable on the high load.
- Present?, Any?, Exists? methods.
‘Present?’ method is really slow. If we’re loading one project, and then loading all of its tasks to check for presence using ‘present?’ this ends up in taking quite a bit of time (~900ms), hurting the performance of the app.
What about ‘Any?’. ‘Any?’ uses SQL count instead of loading each task, resulting in a faster, more performant result (from ~900ms down to ~100ms). But we don’t really need a count of tasks.
- Adding an index to your models column.
Without an index, the database engine would need to check every record in the projects table, one by one, until a match is found. However, if we introduce an index on the ‘projects’ table, as in the following example, the lookup will be much, much faster.
Logging will always have a small impact on the performance of your Rails app, particularly when logging to disk.
Using the :debug level will have a greater performance penalty than :fatal, as a far greater number of strings are being evaluated and written to the log output (e.g. disk).
Another potential pitfall is too many calls to Logger in your code. Therefore, it’s recommended to pass blocks to the logger methods
- Preload Active Record Associations.
Let’s say on a users profile page we would like to show a listing of comments from the particular user. To avoid having many different queries created in the database when the user commented different posts, we should use includes() method.
- Use Caching
Caching common pages or actions can give a pretty dramatic performance increase. Even if your pages don’t contain calls to the database or heavy dynamic content, the simple fact of avoiding rendering overheads for partials or content blocks can increase performance enough to make it worthwhile.
p.s. Explore the series of articles about ‘Ruby on Rails and DataTables plug-in‘ prepared by the other Syndicode Ruby on Rails developer, Vadim Tsvid!
p.p. s. Note, that If your project looks the same and you don’t really want to cope with it yourself, Syndicode can easily do this for you! We love coding and can help you no matter how difficult your project is! Use the contact form on our site to implement your idea to life!