+ =比''.join()更快?

时间:2018-08-30 21:01:45

标签: python python-3.x

因此,我被告知,连接字符串是一个非常昂贵的过程,我们最好将其附加到列表中然后再将它们加入,而这整个都是在Internet上进行的。毕竟,不创建临时字符串总比这样做更好。 但是,当我在Python 3.7上进行测试时,似乎相反。 我在这里有两个功能。 editText1应该比def editText0(text, slices): # text is the string to be edited. # slices should be in the form of {(start0, end0): chars0, (start1, end1): chars1 ...}. # text is going to be split into lices by '\n' # slicing is going to be applied to every line individually # the new text is going to be in the form of text[n][start0:end0] + chars0 + text[n + 1][start1:end1] + chars1 + ... text = text.split('\n')[:-1] # get lines. We don't need the last item in the list since it is empty, hence [:-1] finalText = '' # fully processed text for line in text: # for every line finalLine = '' # final state of the current line for ((start, end), chars) in slices.items(): finalLine += line[start : end] + chars finalText += finalLine finalText += '\n' return finalText def editText1(text, slices): text = text.split('\n')[:-1] # get lines. We don't need the last item in the list since it is empty, hence [:-1] finalText = "\n".join(''.join(line[start : end] + chars for ((start, end), chars) in slices.items()) for line in text) return finalText text = 'abcdefghijklmnopqrstuvwxyz\n' * 4 # 4 lines, each 26 characters and a '\n' slices = {(0, 11): "-", (0, 26): "~", (20, 24): ""}

print(timeit.timeit("editText0(text, slices)", "from __main__ import editText0, text, slices"))
print(timeit.timeit("editText1(text, slices)", "from __main__ import editText1, text, slices"))

我给他们计时的时候:

{{1}}

输出为5.162253748000012和7.014296320999847。基于串联的功能几乎总是快2整秒。

这是怎么回事?互联网上有关此问题的大多数讨论似乎是从很久以前开始的,是否是因为Python本身进行了某种优化?在2018年串联字符串的最佳方法是什么?

0 个答案:

没有答案