Skip to content

[mypyc] Don't box ints, floats and bools for type() - #22441

Closed
rheard wants to merge 1 commit into
python:masterfrom
rheard:mypyc-type-of-unboxed
Closed

rheard wants to merge 1 commit into
python:masterfrom
rheard:mypyc-type-of-unboxed

Conversation

@rheard

@rheard rheard commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

type(x) boxed x if it was an unboxed int, float or bool, and then read the type of the box. That allocates an object for every float and every int outside the small-int cache, only to free it again. For example, in

def count_exact_ints(n: int) -> int:
    k = 0
    for i in range(10**6, 10**6 + n):
        if type(i) is int:
            k += 1
    return k

the check was

    r8 = box(int, i)
    r9 = CPy_TYPE(r8)
    dec_ref r8
    r10 = load_address PyLong_Type
    r11 = r9 == r10
    dec_ref r9

Now type(x) doesn't box:

  • float, bool and fixed-width ints (i64, u16 and so on): the type doesn't depend on the value, so it's a
    load_address of PyFloat_Type, PyBool_Type or PyLong_Type, like a reference to float, bool or int.
    The argument is still evaluated. type(x) is float is then a comparison of two constant addresses, without any
    reference counting, which the C compiler can fold.
  • int: a new primitive, CPyTagged_Type(). A short int boxes to an exact int, so that's its type. A long int
    is 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

    r8 = CPyTagged_Type(i)
    dec_ref i :: int
    r9 = load_address PyLong_Type
    r10 = r8 == r9
    dec_ref r8

Performance

Best of 40 rounds. ns per iteration of a compiled loop like the one above:

loop body master this PR
if type(i) is int, i past 10**6 16.1 2.8 5.8x
if type(i & 255) is int (small int cache) 5.4 4.0 1.4x
if type(x) is float (and x += 1.0) 7.8 2.1 3.7x

For a float, a bool or a fixed-width int such as i64, type(x) is now a constant, so type(x) is int with x: i64 doesn't depend on x at all (master: 15.8 ns per iteration, which was mostly boxing x).

@rheard rheard closed this Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant