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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With