Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Created March 1, 2018 04:37
Show Gist options
  • Save StevenJL/466f9501a83ed2560b356c58d0134999 to your computer and use it in GitHub Desktop.
Save StevenJL/466f9501a83ed2560b356c58d0134999 to your computer and use it in GitHub Desktop.
require "benchmark"
user = User.find_by_name("Teemo")
# See the time it takes to count the comments of a post in an n+1 query
puts Benchmark.realtime { user.posts.each { |post| puts post.comments.count } }
# See the time it takes to count the comments of a post with eager-loading
# Should be faster
puts Benchmark.realtime { user.includes(:posts).posts.each { |post| puts post.comments.count } }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment