bpo-36793: Remove unneeded __str__ definitions. by serhiy-storchaka · Pull Request #13081 · python/cpython
The overhead is very small. It is just few memory reads, comparison an one C function call. It is comparable with Py_INCREF/Py_DECREF.
static PyObject * object_str(PyObject *self) { unaryfunc f; f = Py_TYPE(self)->tp_repr; if (f == NULL) f = object_repr; return f(self); }
In the worst case, for booleans, where __repr__() just returns a precreated string, I got the difference around 1.5 times of the standard deviation:
$ ./python -m perf timeit -s "a = [True] * 10**3" -- "list(map(str, a))"
Unpatched: Mean +- std dev: 94.3 us +- 2.8 us
Patched: Mean +- std dev: 98.1 us +- 3.2 us
In other cases it is smaller than the standard deviation (actually there is a large probability that you get better result with the patched version).
$ ./python -m perf timeit -s "a = [12345] * 10**3" -- "list(map(str, a))"
Unpatched: Mean +- std dev: 183 us +- 4 us
Patched: Mean +- std dev: 185 us +- 4 us
$ ./python -m perf timeit -s "a = [12.345] * 10**3" -- "list(map(str, a))"
Unpatched: Mean +- std dev: 451 us +- 12 us
Patched: Mean +- std dev: 447 us +- 13 us
$ ./python -m perf timeit -s "a = [12.345j] * 10**3" -- "list(map(str, a))"
Unpatched: Mean +- std dev: 670 us +- 17 us
Patched: Mean +- std dev: 669 us +- 19 us
It is insignificant with the time of creating new string.