viphat / til

Today I Learned
http://notes.viphat.work
0 stars 1 forks source link

[PluralSight] - Rails 4.1 Performance Fundamentals - Module 3 - Database #252

Open viphat opened 6 years ago

viphat commented 6 years ago

Database

Profiling

Pagination

Indexing

N+1 Queries

Using gem bullet to detect N+1 Queries And missing counter_cache

One way to quickly add counter_cache to existing table.

UPDATE courses
SET enrollments_count = (
  SELECT COUNT(*) FROM courses
  WHERE course_id = courses.id
)

Rack Mini Profiler and Flamegraph

Select only the columns that you need

select and pluck

Rails Query Cache

Caches identical SQL queries in memory Busted when you write Busted when the request is finished Scoped per thread

New Relic and Rails Panel

Do not order by created_at

Because created_at is not indexed by default and we can use id column instead.

Making Multiple Writes? Use a Transaction

Because Database works very hard every time you commit and it has to resolve that commit with the rest of the system. It makes it a lot easier on the database if you combine those writes into a single transaction because then it only has to do that resolution once at the end of all of them.

Use find_each instead of each when load tons of rows

find_each is slightly slower but it uses less memory.