根据 John Fouhy 的回答,除非必须,否则不要优化,但如果您在这里提出这个问题,可能正是因为您必须。就我而言,我需要从字符串变量中组装一些 URL……快。我注意到(到目前为止)似乎没有人在考虑字符串格式方法,所以我想我会尝试一下,并且主要是出于轻微的兴趣,我想我会将字符串插值运算符扔在那里以获得更好的测量值。老实说,我认为这两种方法都不会叠加到直接的“+”操作或“.join()”中。但猜猜怎么了?在我的 Python 2.7.5 系统上,字符串插值运算符将它们全部统治,而 string.format() 的表现最差:
# concatenate_test.py
from __future__ import print_function
import timeit
domain = 'some_really_long_example.com'
lang = 'en'
path = 'some/really/long/path/'
iterations = 1000000
def meth_plus():
'''Using + operator'''
return 'http://' + domain + '/' + lang + '/' + path
def meth_join():
'''Using ''.join()'''
return ''.join(['http://', domain, '/', lang, '/', path])
def meth_form():
'''Using string.format'''
return 'http://{0}/{1}/{2}'.format(domain, lang, path)
def meth_intp():
'''Using string interpolation'''
return 'http://%s/%s/%s' % (domain, lang, path)
plus = timeit.Timer(stmt="meth_plus()", setup="from __main__ import meth_plus")
join = timeit.Timer(stmt="meth_join()", setup="from __main__ import meth_join")
form = timeit.Timer(stmt="meth_form()", setup="from __main__ import meth_form")
intp = timeit.Timer(stmt="meth_intp()", setup="from __main__ import meth_intp")
plus.val = plus.timeit(iterations)
join.val = join.timeit(iterations)
form.val = form.timeit(iterations)
intp.val = intp.timeit(iterations)
min_val = min([plus.val, join.val, form.val, intp.val])
print('plus %0.12f (%0.2f%% as fast)' % (plus.val, (100 * min_val / plus.val), ))
print('join %0.12f (%0.2f%% as fast)' % (join.val, (100 * min_val / join.val), ))
print('form %0.12f (%0.2f%% as fast)' % (form.val, (100 * min_val / form.val), ))
print('intp %0.12f (%0.2f%% as fast)' % (intp.val, (100 * min_val / intp.val), ))
结果:
# python2.7 concatenate_test.py
plus 0.360787868500 (90.81% as fast)
join 0.452811956406 (72.36% as fast)
form 0.502608060837 (65.19% as fast)
intp 0.327636957169 (100.00% as fast)
如果我使用更短的域和更短的路径,插值仍然会胜出。不过,如果字符串越长,差异就越大。
现在我有了一个不错的测试脚本,我还在 Python 2.6、3.3 和 3.4 下进行了测试,结果如下。在 Python 2.6 中,加号运算符是最快的!在 Python 3 上,加入胜出。注意:这些测试在我的系统上非常可重复。因此,“plus”在 2.6 上总是更快,“intp”在 2.7 上总是更快,而“join”在 Python 3.x 上总是更快。
# python2.6 concatenate_test.py
plus 0.338213920593 (100.00% as fast)
join 0.427221059799 (79.17% as fast)
form 0.515371084213 (65.63% as fast)
intp 0.378169059753 (89.43% as fast)
# python3.3 concatenate_test.py
plus 0.409130576998 (89.20% as fast)
join 0.364938726001 (100.00% as fast)
form 0.621366866995 (58.73% as fast)
intp 0.419064424001 (87.08% as fast)
# python3.4 concatenate_test.py
plus 0.481188605998 (85.14% as fast)
join 0.409673971997 (100.00% as fast)
form 0.652010936996 (62.83% as fast)
intp 0.460400978001 (88.98% as fast)
# python3.5 concatenate_test.py
plus 0.417167026084 (93.47% as fast)
join 0.389929617057 (100.00% as fast)
form 0.595661019906 (65.46% as fast)
intp 0.404455224983 (96.41% as fast)
经验教训:
- 有时,我的假设完全错误。
- 针对系统环境进行测试。您将在生产环境中运行。
- 字符串插值还没有死!
tl;博士:
- 如果您使用 2.6,请使用 + 运算符。
- 如果您使用的是 2.7,请使用“%”运算符。
- 如果您使用的是 3.x,请使用 ''.join()。