From c59e84485224156866ba5260d5b0f8bb94aca85d Mon Sep 17 00:00:00 2001 From: Lephe Date: Wed, 7 Jul 2021 17:26:22 +0200 Subject: [PATCH] forum: count comments for all presented topics in a single request (#63) It appears as though performing a lot of requests is the most costly aspect of listing comment counts per topic; this change aims to address that by reading all the counts in a single request. On my computer, this changes loading times from an absolute 100-200 ms to 50-100 ms most of the time. The request impact is not easy to measure as a couple ms is small enough to fall in the range of disk access and other semi-random events. --- app/routes/forum/index.py | 14 +++++++++++++- app/templates/forum/forum.html | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/app/routes/forum/index.py b/app/routes/forum/index.py index dbdbdb8..023b881 100644 --- a/app/routes/forum/index.py +++ b/app/routes/forum/index.py @@ -80,4 +80,16 @@ def forum_page(f, page=1): topics = f.topics.order_by(Topic.date_created.desc()).paginate( page, Forum.TOPICS_PER_PAGE, True) - return render('/forum/forum.html', f=f, topics=topics, form=form) + # Count comments; this direct request avoids performing one request for + # each topic.thread.comments.count() in the view, which the database + # doesn't really appreciate performance-wise. + req_comment_counts = \ + "SELECT thread_id, COUNT(*) FROM comment WHERE " + \ + " OR ".join(f"thread_id={t.thread.id}" for t in topics.items) + \ + " GROUP BY thread_id" + + comment_counts = db.session.execute(req_comment_counts) + comment_counts = dict(list(comment_counts)) + + return render('/forum/forum.html', f=f, topics=topics, form=form, + comment_counts=comment_counts) diff --git a/app/templates/forum/forum.html b/app/templates/forum/forum.html index 932fa42..dbd5783 100644 --- a/app/templates/forum/forum.html +++ b/app/templates/forum/forum.html @@ -23,7 +23,7 @@ {{ t.title }} {{ t.author.name }} {{ t.date_created | date }} - {{ t.thread.comments.count() }} + {{ comment_counts[t.thread.id] }} {{ t.views }} {% endfor %}