So it's a CPython thing, not quite sure that it has same behaviour with other implementations.
But '{0}'.format()
is faster than str()
and '{}'.format()
. I'm posting results from Python 3.5.2, but, I tried it with Python 2.7.12 and the trend is the same.
%timeit q=['{0}'.format(i) for i in range(100, 100000, 100)]
%timeit q=[str(i) for i in range(100, 100000, 100)]
%timeit q=['{}'.format(i) for i in range(100, 100000, 100)]
1000 loops, best of 3: 231 µs per loop
1000 loops, best of 3: 298 µs per loop
1000 loops, best of 3: 434 µs per loop
From the docs on object.__str__(self)
Called by
str(object)
and the built-in functionsformat()
andprint()
to compute the “informal” or nicely printable string representation of an object.
So, str()
and format()
call same object.__str__(self)
method, but where does that difference in speed come from?
UPDATE
as @StefanPochmann and @Leon noted in comments, they get different results. I tried to run it with python -m timeit "..."
and, they are right, because the results are:
$ python3 -m timeit "['{0}'.format(i) for i in range(100, 100000, 100)]"
1000 loops, best of 3: 441 usec per loop
$ python3 -m timeit "[str(i) for i in range(100, 100000, 100)]"
1000 loops, best of 3: 297 usec per loop
$ python3 -m timeit "['{}'.format(i) for i in range(100, 100000, 100)]"
1000 loops, best of 3: 420 usec per loop
So it seems that IPython is doing something strange...
NEW QUESTION: What is preferred way to convert an object to str
by speed?