PIL._binary: Use int.to_bytes() for faster conversion - #9981
Open
akx wants to merge 1 commit into
Open
Conversation
akx
marked this pull request as ready for review
September 10, 2026 13:21
Contributor
Author
|
I suspect our benchmark suite isn't really testing the write side of plugins that use |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
int.to_bytes()has been a thing since Python 3.2, and it's faster thanstruct.packhaving to parse that spec and all that on every invocation. This micro-benchmarks to be 1.2x to 1.5x faster on my machine for essentially free.Fun fact
There's an upcoming CPython 3.16 optimization that will further help
o8()memory-wise (since theint.to_bytes(..., 1)call will end up just returning one of the singleton byteses).Fun related fact
We could borrow that idea, namely something like
but it felt a little too much. It would save about 42 bytes of allocations for every
o8()call before 3.16 lands, as well as some time (microbenchmarked to be 2.6x faster), but it's a bit weird - I suspect better gains would be had by looking at the call sites foro8()to see if they really need to pack a single byte at a time. (The weird construction for the tuple ensures we do actually get references to the immortal singleton byteses, not new allocations.)