Rendering thousands of records on one page is slow. Pagination loads one page at a time and keeps large lists fast.
Important
Work on this lesson in
advisormode.
Learning goals
- You can explain why rendering a large collection on one page is slow — queries, object instantiation, rendering — and how pagination avoids it.
- You can add pagination to a list with a gem (e.g.
will_paginate) and style its controls to match the app. - You can read the queries pagination produces (a
LIMIT/OFFSETquery and a count) and explain what each is for. - You can read a request in the development log and tell where its time went, e.g. views vs. database.
- You can measure what a user actually experiences: load time and response size in the DevTools Network tab, with throttling simulating a slow connection.
- You can create large amounts of test data quickly, e.g. inside a single transaction.
Resources
Read what's new to you, skim what's familiar, skip what you already master. Stop when you can meet the learning goals.
Your agent can also generate an overview, a tutorial or an explanation for anything here, tailored to what you already know. Just ask.
- 📄
will_paginate
Show archive.org snapshot
— README of the gem used in the exercise:
paginate,will_paginateview helper, customizing the rendered links - 📄 Rails Guide: Active Record Query Interface — limit and offset Show archive.org snapshot — what pagination does in SQL
- 📄 pagy Show archive.org snapshot — a faster, framework-agnostic alternative you'll meet in some projects
- 📄 Chrome DevTools: Inspect network activity Show archive.org snapshot — the Network tab: request rows, timings, response sizes, throttling
Exercises
Work on your local development server throughout — no staging needed here.
Create a slow page
- Create 7500 movies in MovieDB (hint: doing it in a single transaction is much faster).
Measure the server
-
tail -f log/development.logand load the movies index. Learn to read the request log: which queries ran, and the finalCompleted 200 OK in …ms (Views: … | ActiveRecord: …)line. Where does the time go?
Measure the browser
- The server time is not what a user feels: the HTML must also travel over the network, and the browser must build the page from it. Open your browser's DevTools, find the Network tab and throttle to "Slow 4G". Reload and find the request row for the index HTML document. How long did it take, and how large is the response?
Paginate
- Use the
will_paginategem to add pagination to MovieDB's list of movies. - Inspect the HTML generated by
will_paginate. Customize the style so it matches the look of your MovieDB. - In the development log, see which queries
will_paginategenerates. What does each of them do? - Repeat both measurements — request log and throttled Network tab — and compare them with the numbers from before.
Posted by Henning Koch to makandra Curriculum (2015-07-08 17:29)