Search code examples
pythonpython-3.xintpython-internals

Python's int function performance


Does Python's built-in function int still try to convert the submitted value even if the value is already an integer?

More concisely: is there any performance difference between int('42') and int(42) caused by conversion algorithm?


Solution

  • As per the comments in the source code,

    Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

    If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base

    So, if the input is a number, __int__ function will be called on that object and the result will be returned. Internally nb_int is an item in PyNumberMethods structure, which corresponds to the __int__ function. As per the latest source code at the time of this writing, long_long is the function which corresponds to the nb_int function, which is defined like this

    long_long(PyObject *v)
    {
        if (PyLong_CheckExact(v))
            Py_INCREF(v);
        else
            v = _PyLong_Copy((PyLongObject *)v);
        return v;
    }
    

    Here PyLong_checkExact is a Macro, which just checks if the current object is really of type long. If it is true, it simply increases the reference count and returns the object as it is, nothing extra is done.

    If the input is in the form of a string, the string has to be converted to a number with PyLong_FromUnicodeObject function.