From d5139931c3cb9c5cbc9827ed0819c1b624ce8505 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 9 Dec 2025 13:55:11 +0000 Subject: [PATCH] Optimize GraphicsContextPdf.fill The optimization replaces `if len(args):` with `if args:` in the condition check. This change provides a 6% speedup by eliminating the overhead of calling the `len()` function. **Key optimization:** - **What**: Changed `if len(args):` to `if args:` - **Why**: In Python, checking truthiness of a collection (`if args:`) is faster than computing its length (`if len(args):`). The `len()` function call adds unnecessary overhead when we only need to know if the collection is non-empty. - **Performance impact**: The line profiler shows the condition check time decreased from 567,824ns to 464,596ns (18% faster on that specific line), contributing to the overall 6% speedup. **How it works:** - Both expressions are functionally equivalent for determining if `args` contains elements - `if args:` directly checks if the tuple is truthy (non-empty), which is a simple pointer/size check - `if len(args):` requires a function call to compute the length, then checks if that result is truthy **Test case analysis:** The optimization shows consistent improvements across most test scenarios: - Best gains (8-15%) when hatch is set or fillcolor is None, where the condition is evaluated but the function returns early - Moderate gains (2-7%) for typical color tuple cases - Minimal impact on edge cases with very large tuples, suggesting the optimization doesn't hurt worst-case performance This is a micro-optimization that provides measurable benefits in a graphics context where the `fill()` method is likely called frequently during rendering operations. --- lib/matplotlib/backends/backend_pdf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 7e3e09f034f5..fcfaaeede9b6 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -2470,7 +2470,7 @@ def fill(self, *args): An optional argument can be used to specify an alternative _fillcolor, as needed by RendererPdf.draw_markers. """ - if len(args): + if args: _fillcolor = args[0] else: _fillcolor = self._fillcolor