Repository navigation
[mypyc] Don't box ints, floats and bools for type() - #22455
Merged
Merged
Conversation
JukkaL
approved these changes
Nov 16, 2026
JukkaL
left a comment
Collaborator
There was a problem hiding this comment.
Thanks, this seems useful, for example when migrating existing code to mypyc which might have these checks.
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.
type(x)boxedxif it was an unboxedint,floatorbool, and then read the type of the box. That allocates an object for everyfloatand every int outside the small-int cache, only to free it again. For example, inthe check was
Now
type(x)doesn't box:float,booland fixed-width ints (i64,u16and so on): the type doesn't depend on the value, so it's aload_addressofPyFloat_Type,PyBool_TypeorPyLong_Type, like a reference tofloat,boolorint.The argument is still evaluated.
type(x) is floatis then a comparison of two constant addresses, without anyreference counting, which the C compiler can fold.
int: a new primitive,CPyTagged_Type(). A short int boxes to an exactint, so that's its type. A long intis an object already, and it can be an instance of a subclass of
int, so the type of that object is returned,as before.
So the check above is now
Performance
Best of 40 rounds. ns per iteration of a compiled loop like the one above:
if type(i) is int,ipast 10**6if type(i & 255) is int(small int cache)if type(x) is float(andx += 1.0)For a
float, aboolor a fixed-width int such asi64,type(x)is now a constant, sotype(x) is intwithx: i64doesn't depend onxat all (master: 15.8 ns per iteration, which was mostly boxingx).