str performance in python

后端 未结 2 1603
暖寄归人
暖寄归人 2021-01-30 04:54

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

2条回答
  •  遇见更好的自我
    2021-01-30 05:37

    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
    

提交回复
热议问题