From 29c1ce8af60ea32c89e7278185df7297221db291 Mon Sep 17 00:00:00 2001 From: Nicolas Fricke Date: Wed, 14 Apr 2021 16:23:50 +0200 Subject: [PATCH] Memoize the `Paginator#page` method This method is invoked multiple times to retrieve the `start_cursor`, the `end_cursor`, and ultimately to return the actual `page` record. By memoizing it, we avoid it from mapping over the `records` again and again and rebuilding all the cursors every time it is invoked. --- CHANGELOG.md | 1 + lib/rails_cursor_pagination/paginator.rb | 12 +++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 956b12d..d0de991 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ These are the latest changes on the project's `master` branch that have not yet ### Fixed - Only trigger one SQL query to load the records from the database and use it to determine if there was a previous / is a next page +- Memoize the `Paginator#page` method which is invoked multiple times to prevent it from mapping over the `records` again and again and rebuilding all cursors ### Added - Description about `order_by` on arbitrary SQL to README.md diff --git a/lib/rails_cursor_pagination/paginator.rb b/lib/rails_cursor_pagination/paginator.rb index fda0bba..21876cb 100644 --- a/lib/rails_cursor_pagination/paginator.rb +++ b/lib/rails_cursor_pagination/paginator.rb @@ -147,11 +147,13 @@ def page_info # # @return [Array] List of hashes, each with a `cursor` and `data` def page - records.map do |item| - { - cursor: cursor_for_record(item), - data: item - } + memoize :page do + records.map do |item| + { + cursor: cursor_for_record(item), + data: item + } + end end end