Have you heard of N+1 questions? If you don't, don't worry - it's a common problem in web development, but we have a handy tool to help us identify and solve it. Let’s talk about gem bullet https://github.com/flyerhzm/bullet!
Instead of simply monitoring queries, Bullet acts as a vigilant guardian, scrutinizing your code for performance bottlenecks. It identifies areas for improvement by flagging N+1 query issues, unnecessary eager loading, and suggesting the use of counter caches.
Imagine writing to all your classmates and their favorite books. You can do this:
This is like an N+1 question. You make one request for list (1), then one request for each classmate (N). If you have 30 classmates, that’s 31 requests! That’s a lot of work and can slow down your website.
A gem bullet is like a friendly robot that looks at your website and tells you when you have made too many requests with N+1. It’s super easy to use:
Best practice is to use Bullet in development mode or custom mode (staging, profile, etc.). For more information, visit https://github.com/flyerhzm/bullet.
Once bullet points out a problem, you can fix it. Instead of asking each classmate individually, you can ask them all at once, "Hey class, what are your favorite books?" This is much faster!
Let's break down why asking everyone at once is faster:
In database terms, this approach of getting all the information at once is called "eager loading". It's like filling up your whole backpack with books in one go, rather than walking back and forth to your locker for each class.
From a coding perspective, we use "eager loading" or "includes" objects to get all the information we need at once.
Blocking N+1 queries can significantly speed up your website. Faster websites keep users happy, use less energy, and can even rank higher in search engines.
Remember that writing efficient code is an important skill for any developer. Tools like gem bullet help us learn and improve our code.