Skip to content

Use @cache instead of precalculating BMP grayscale palette - #10593

Open
radarhere wants to merge 1 commit into
python-pillow:mainfrom
radarhere:cache
Open

radarhere wants to merge 1 commit into
python-pillow:mainfrom
radarhere:cache

Conversation

@radarhere

Copy link
Copy Markdown
Member

#10580 (comment)

Small thing, but it could be worth it to return these from a function marked with @cache instead of precomputing them into the .py (and .pyc).

@radarhere

Copy link
Copy Markdown
Member Author

@akx @nietras please review

@nietras

nietras commented Nov 23, 2026

Copy link
Copy Markdown

@radarhere only downside as far as I can tell here is that the way this is cached requires a tuple allocation (as that is the key into the cache), besides of course the one off start/creation cost. LLM proposes changing to simply create all four cached byte arrays in one method , not sure if worth it. As far as I can tell runtime is about the same and still much faster than before.

@cache
def _grayscale_palettes():
    # Construct the four tables once.
    return rgb_ramp, bgrx_ramp, rgb_monochrome, bgrx_monochrome

def _is_grayscale_palette(palette, colors, padding):
    index = (2 if colors == 2 else 0) + padding - 3
    return _grayscale_palettes()[index].startswith(palette)

@akx akx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm (sorry, been sick in bed all day). With the original method, every import of the BMP plugin (IOW, every import of Pillow) paid the memory price of all of the LUTs, so I think this is the better tradeoff.

@hugovk

hugovk commented Nov 23, 2026

Copy link
Copy Markdown
Member

Can we measure memory and speed?

@radarhere

radarhere commented Nov 23, 2026 •

Copy link
Copy Markdown
Member Author

With the image from #10574 (comment), main shows

$ python3 -m timeit -s "from PIL import Image; im = Image.open('grayscale-32x32.bmp')"
100000000 loops, best of 5: 2.72 nsec per loop

There is no consistent difference with this PR.

@radarhere

Copy link
Copy Markdown
Member Author

memory_profiler shows no consistent difference.

Line #    Mem usage    Increment  Occurrences   Line Contents
=============================================================
     3     23.5 MiB     23.5 MiB           1   @profile
     4                                         def demo():
     5     25.0 MiB      1.5 MiB           1       from PIL import Image
     6     25.2 MiB      0.2 MiB           1       im = Image.open('grayscale-32x32.bmp')

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants