Cache pages at the start of drawing, not the end. #4932
Merged
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.
When we finish drawing a PageView, we add it to the PageView cache (this happens within the pageViewDrawCallback function within PageView.draw()). Once in the cache, it will be destroyed (via PageView.destroy()), once 20 more PageViews have been drawn, and its canvas memory can then be freed.
This is good, except it falls down in one case: when scrolling really quickly through a document, we start drawing each page but then usually move past it before it finishes drawing. When this happen, its drawing pauses because it's no longer the highest-priority page (this happens within renderContext.continueCallback in PageView.draw()).
At this point such a page is not in the cache, so it can't be destroyed. If you scroll quickly through a lot of pages, most of them will end up in this state. The only way such a page can be destroyed is by navigating back to it, whereupon its drawing will resume (within PDFView.renderView) and complete, and
it will be put into the cache.
(Now, it appears that the browser can free the canvas memory even if the page isn't destroyed. But in Firefox, this apparently doens't happen until the canvas memory has been unused for 10s of seconds, and it's very easy for canvas memory consumption to spike massively in that time.)
Fortunately, there's an easy way to fix this: just put each page in the cache as soon as it starts drawing, instead of when it finishes drawing.
This makes a big difference in practice. Scrolling through three large documents on my Mac, peak RSS dropped greatly: