在分析一段 python 代码(python 2.6
到 3.2
)时,我发现
str
方法将对象(在我的例子中是整数)转换为字符串几乎比使用字符串格式化慢一个数量级。
这是基准
>>> from timeit import Timer
>>> Timer('str(100000)').timeit()
0.3145311339386332
>>> Timer('"%s"%100000').timeit()
0.03803517023435887
有人知道为什么会这样吗? 我错过了什么吗?
最佳答案
'%s' % 100000
由编译器计算,在运行时等效于常量。
>>> import dis
>>> dis.dis(lambda: str(100000))
8 0 LOAD_GLOBAL 0 (str)
3 LOAD_CONST 1 (100000)
6 CALL_FUNCTION 1
9 RETURN_VALUE
>>> dis.dis(lambda: '%s' % 100000)
9 0 LOAD_CONST 3 ('100000')
3 RETURN_VALUE
带有运行时表达式的 %
并不(显着)快于 str
:
>>> Timer('str(x)', 'x=100').timeit()
0.25641703605651855
>>> Timer('"%s" % x', 'x=100').timeit()
0.2169809341430664
请注意 str
仍然稍慢,正如@DietrichEpp 所说,这是因为 str
涉及查找和函数调用操作,而 %
编译为单个立即字节码:
>>> dis.dis(lambda x: str(x))
9 0 LOAD_GLOBAL 0 (str)
3 LOAD_FAST 0 (x)
6 CALL_FUNCTION 1
9 RETURN_VALUE
>>> dis.dis(lambda x: '%s' % x)
10 0 LOAD_CONST 1 ('%s')
3 LOAD_FAST 0 (x)
6 BINARY_MODULO
7 RETURN_VALUE
当然,对于我测试过的系统(CPython 2.7),以上是正确的;其他实现可能会有所不同。
关于python - python中的str性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10530315/