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 intege
One reason that comes to mind is the fact that str(100000)
involves a global lookup, but "%s"%100000
does not. The str
global has to be looked up in the global scope. This does not account for the entire difference:
>>> Timer('str(100000)').timeit()
0.2941889762878418
>>> Timer('x(100000)', 'x=str').timeit()
0.24904918670654297
As noted by thg435,
>>> Timer('"%s"%100000',).timeit()
0.034214019775390625
>>> Timer('"%s"%x','x=100000').timeit()
0.2940788269042969