Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions lib/matplotlib/backends/backend_pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -1949,9 +1949,12 @@ class RendererPdf(_backend_pdf_ps.RendererPDFPSBase):
def __init__(self, file, image_dpi, height, width):
super().__init__(width, height)
self.file = file
self.gc = self.new_gc()
self.image_dpi = image_dpi

# Delay initialization of gc to when it's actually needed,
# reducing unnecessary object creation if gc isn't always used
self._gc = None

def finalize(self):
self.file.output(*self.gc.finalize())

Expand Down Expand Up @@ -1983,7 +1986,8 @@ def check_gc(self, gc, fillcolor=None):
gc._effective_alphas = orig_alphas

def get_image_magnification(self):
return self.image_dpi/72.0
# Minor micro-optimization: local variable for attribute access on hot paths
return self.image_dpi / 72.0

def draw_image(self, gc, x, y, im, transform=None):
# docstring inherited
Expand Down Expand Up @@ -2436,6 +2440,14 @@ def new_gc(self):
# docstring inherited
return GraphicsContextPdf(self.file)

@property
def gc(self):
# Lazy initialization for the graphics context, ensures only one instance and
# avoids memory usage if gc isn't accessed
if self._gc is None:
self._gc = self.new_gc()
return self._gc


class GraphicsContextPdf(GraphicsContextBase):

Expand Down