Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
We're currently calling the main method, and then looping over the result. In each loop, we call the method again so that we can get the length. See manual_section.html.erb, which does roughly:
... the effect of this is that we run the main method n times, where n is the number of
<h2>
elements in the body. This results in us spending a lot of time parsing the same document and running the same CSS / XPath selectors on it, which adds up to a lot of time.Memoizing the result of the main method shaves several seconds off the time to render www.gov.uk/guidance/complete-the-school-census/data-items-2024-to-2025 on my machine.
The flamegraph before these changes (using the wonderful rack-mini-profiler) shows manual_section.html.erb taking over 2 seconds to render:
Note that
ManualSectionPresenter#main
is called many times.After the changes in this PR, this reduces to 186ms:
These flamegraphs also identified a further ~70ms we could save by memoizing the intro method, so I've done that too.
I did look at some other optimizations (e.g. traversing the nokogiri document manually, instead of using css / xpaths), but once it's memoized those only save microseconds so it's not worth it.