From e77c17fef43714decfb8e4108916d524e30d97fa Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Sun, 22 Jun 2025 23:11:56 +0200 Subject: [PATCH] Use collections.deque to store animation cache data. deques are exactly suited for the task at hand, and should be (here, marginally) more efficient than repeatedly slicing off the start of the list. Also drop unneeded reference to old_frame_seq (the iterator already keeps that data alive). --- lib/matplotlib/animation.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/animation.py b/lib/matplotlib/animation.py index c6ff7702d992..8756cb0c1439 100644 --- a/lib/matplotlib/animation.py +++ b/lib/matplotlib/animation.py @@ -1,5 +1,6 @@ import abc import base64 +import collections import contextlib from io import BytesIO, TextIOWrapper import itertools @@ -1708,13 +1709,13 @@ def iter_frames(frames=frames): self._cache_frame_data = cache_frame_data # Needs to be initialized so the draw functions work without checking - self._save_seq = [] + self._save_seq = collections.deque([], self._save_count) super().__init__(fig, **kwargs) # Need to reset the saved seq, since right now it will contain data # for a single frame from init, which is not what we want. - self._save_seq = [] + self._save_seq.clear() def new_frame_seq(self): # Use the generating function to generate a new frame sequence @@ -1727,8 +1728,7 @@ def new_saved_frame_seq(self): if self._save_seq: # While iterating we are going to update _save_seq # so make a copy to safely iterate over - self._old_saved_seq = list(self._save_seq) - return iter(self._old_saved_seq) + return iter([*self._save_seq]) else: if self._save_count is None: frame_seq = self.new_frame_seq() @@ -1773,13 +1773,12 @@ def _init_draw(self): 'return a sequence of Artist objects.') for a in self._drawn_artists: a.set_animated(self._blit) - self._save_seq = [] + self._save_seq.clear() def _draw_frame(self, framedata): if self._cache_frame_data: # Save the data for potential saving of movies. self._save_seq.append(framedata) - self._save_seq = self._save_seq[-self._save_count:] # Call the func with framedata and args. If blitting is desired, # func needs to return a sequence of any artists that were modified.