按照约翰·福伊(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上,join胜出。注意:这些测试在我的系统上是非常可重复的。因此,“ 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; dr:
- 如果使用2.6,请使用+运算符。
- 如果您使用的是2.7,请使用'%'运算符。
- 如果您使用的是3.x,请使用''.join()。