%
的性能比我测试中的format
要好。
测试代码:
Python 2.7.2:
import timeit
print 'format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')")
print '%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')")
结果:
> format: 0.470329046249
> %: 0.357107877731
Python 3.5.2
import timeit
print('format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')"))
print('%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')"))
结果
> format: 0.5864730989560485
> %: 0.013593495357781649
看起来在Python2中,差别很小,而在Python3中,%
比format
快得多。
感谢@Chris Cogdon提供示例代码。
编辑1:
2019年7月再次在Python 3.7.2中进行了测试。
结果:
> format: 0.86600608
> %: 0.630180146
没有太大区别。我猜Python正在逐渐改进。
Edit 2:
在有人在评论中提到了Python 3的f-string之后,我在Python 3.7.2下对以下代码进行了测试:
import timeit
print('format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')"))
print('%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')"))
print('f-string:', timeit.timeit("f'{1}{1.23}{\"hello\"}'"))
结果:
format: 0.8331376779999999
%: 0.6314778750000001
f-string: 0.766649943
似乎在性能上,f-string仍比%
慢但优于format
。