From 49f0cc16ba07ae021d9b6bf2842ce877cb79f2b8 Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 28 Mar 2023 18:09:22 +1100 Subject: [PATCH] PERF: optimise serialization for topic tracking state (#20860) This corrects two issues: 1. We were double serializing topic tracking state (as_json calls were not cached) 2. We were inefficiently serializing items by instantiating extra objects --- app/controllers/application_controller.rb | 6 ++++-- app/serializers/topic_tracking_state_item_serializer.rb | 4 ++++ app/serializers/topic_tracking_state_serializer.rb | 6 +++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 42099571bef..cbed26f8560 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -653,8 +653,10 @@ class ApplicationController < ActionController::Base report = TopicTrackingState.report(current_user) serializer = TopicTrackingStateSerializer.new(report, scope: guardian, root: false) - store_preloaded("topicTrackingStates", MultiJson.dump(serializer.as_json[:data])) - store_preloaded("topicTrackingStateMeta", MultiJson.dump(serializer.as_json[:meta])) + hash = serializer.as_json + + store_preloaded("topicTrackingStates", MultiJson.dump(hash[:data])) + store_preloaded("topicTrackingStateMeta", MultiJson.dump(hash[:meta])) end def custom_html_json diff --git a/app/serializers/topic_tracking_state_item_serializer.rb b/app/serializers/topic_tracking_state_item_serializer.rb index 31df3ad67a3..919a645294a 100644 --- a/app/serializers/topic_tracking_state_item_serializer.rb +++ b/app/serializers/topic_tracking_state_item_serializer.rb @@ -28,4 +28,8 @@ class TopicTrackingStateItemSerializer < ApplicationSerializer def include_is_category_topic? object.respond_to?(:category_topic_id) end + + def object=(value) + @object = value + end end diff --git a/app/serializers/topic_tracking_state_serializer.rb b/app/serializers/topic_tracking_state_serializer.rb index d7a3384800a..37294c154c6 100644 --- a/app/serializers/topic_tracking_state_serializer.rb +++ b/app/serializers/topic_tracking_state_serializer.rb @@ -4,8 +4,12 @@ class TopicTrackingStateSerializer < ApplicationSerializer attributes :data, :meta def data + serializer = TopicTrackingStateItemSerializer.new(nil, scope: scope, root: false) + # note we may have 1000 rows, avoiding serializer instansitation saves significant time + # for 1000 rows this takes it down from 10ms to 3ms on a reasonably fast machine object.map do |item| - TopicTrackingStateItemSerializer.new(item, scope: scope, root: false).as_json + serializer.object = item + serializer.as_json end end