慎用Python的格式化字符串
2009 3 17 12:53 PM 2819次查看
虽然格式化字符串书写方便,但如果不注意写法的话,性能可能还不及__add__方法。
from time import time
TIMES = 100000
t = time()
for i in xrange(TIMES):
s = '123' + str(i)
print time() - t
t = time()
for i in xrange(TIMES):
s = '123%d' % i
print time() - t
t = time()
for i in xrange(TIMES):
s = str(i) + '123' + str(i)
print time() - t
t = time()
for i in xrange(TIMES):
s = '%d123%d' % (i, i)
print time() - t
t = time()
for i in xrange(TIMES):
s = '%(n)123%(n)' % {'n' : i}
print time() - t
t = time()
for i in xrange(TIMES):
s = str(i) + '1' + str(i) + '2' + str(i) + '3' + str(i)
print time() - t
t = time()
for i in xrange(TIMES):
s = '%d1%d2%d3%d' % (i, i, i, i)
print time() - t
t = time()
for i in xrange(TIMES):
s = '%(n)1%(n)2%(n)3%(n)' % {'n' : i}
print time() - t
t = time()
for i in xrange(TIMES):
s = '%(a)1%(b)2%(c)3%(d)' % {'a' : i, 'b' : i, 'c' : i, 'd' : i}
print time() - t
结果:0.18700003624从结果上来看,少量的__add__方法调用比使用元组的格式化字符串要快,而使用字典的格式化字符串则是最快的方法。
0.203999996185
0.327999830246
0.360000133514
0.155999898911
0.671999931335
0.656000137329
0.141000032425
0.18700003624
不过也不能一律用字典,毕竟书写比较麻烦,而且只使用一次是无法用字典的(至少我这显示:ValueError: incomplete format)。
0条评论 你不来一发么↓