Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 342
vaultah Avatar asked Feb 23 '14 09:02

vaultah


2 Answers

This is handled in function long_long in Objects/longobject.c, as explained in more detail by thefourtheye:

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

So, when the argument is already an int, the reference count is incremented and the same object returned.

You can assume similar behavior for immutable types in general,. For example, tuple(mytuple) returns a new reference to mytuple, while, by contrast, list(mylist) creates a copy of mylist.

like image 118
Janne Karila Avatar answered Oct 02 '22 14:10

Janne Karila


If you pass an int object to int(), you get the same object back (CPython 3.3.2):

>>> a = 1000 * 1000 # large enough to avoid interning
>>> b = int(a)
>>> a is b
True

I don't know what you mean by "algorithmic performance difference", but it doesn't create a new object.

like image 38
jonrsharpe Avatar answered Oct 02 '22 14:10

jonrsharpe