How to write fast code in Ruby on Rails

  1. In Rails
  • Cache all the things.
  • Throttle any operation that can’t be cached. rack-attack and rack-throttle can help throttle unwanted requests.
  • Consciously minimize dependencies. They will turn into liabilities as projects grow.

2. In Ruby

  • Use metaprogramming sparingly to prevent unnecessary slowness.
  • Think about how your code will scale with more data. Know the difference between O(n) and O(1).
  • Avoid mutating global state while leveraging mutation on the local state.

3. In Active Record (Rails’ default ORM)

  • Know when queries get executed and what causes them to get evaluated.
  • Index the columns you need to query.
  • Use select and pluck to select only what you need. By default, Active Record selects all columns in SQL with SELECT *

Full post here, 8 mins read