Benchmarking Rails apps in 5 bullets

  1. When in doubt, measure. Twice!
  2. For ad-hoc/napkin estimates, I use { …the code… } to size up the performance of Ruby code.
  3. When I want to do The Science to compare approaches, I use benchmark-ips. It works a lot like Benchmark, but does all the cold start, iteration, and math for you. It’s great, thanks Evan!
  4. When it comes to code that interacts with databases (Postgres, ElasticSearch, HTTP APIs, Redis, etc.) it is almost always the case that one big query is far faster than queries inside a loop (e.g., N+1 queries)
  5. Ruby performance is often limited by creating many objects and the time it takes for the garbage collector to find/free them up afterwards. This is sometimes not the case in recent Ruby versions (see #1).

Bonus useful tools:

  • bumbler – profile loading gems from your Gemfile at application boot. In most Rails apps, there are several seconds of savings to find in lazy loading rarely loaded libraries.
  • active-record-query-trace: shows the call-site and last few stack frames for every query in your development log. Super handy for “where is this blasted query coming from?”