While profiling a piece of python code (python 2.6 up to 3.2), I discovered that the
str method to convert an object (in my case an integer) to a string is almost an order of magnitude slower than using string formatting.
Here is the benchmark
>>> from timeit import Timer
>>> Timer('str(100000)').timeit()
0.3145311339386332
>>> Timer('"%s"%100000').timeit()
0.03803517023435887
Does anyone know why this is the case?
Am I missing something?
'%s' % 100000is evaluated by the compiler and is equivalent to a constant at run-time.%with a run-time expression is not (significantly) faster thanstr:Do note that
stris still slightly slower, as @DietrichEpp said, this is becausestrinvolves lookup and function call operations, while%compiles to a single immediate bytecode:Of course the above is true for the system I tested on (CPython 2.7); other implementations may differ.