gpt4 book ai didi

python - Python 中的字符串加法真的比使用 join 慢吗?

转载 作者:行者123 更新时间:2023-11-30 22:27:21 25 4
gpt4 key购买 nike

此问题引用Is list join really faster than string concatenation in python?https://waymoot.org/home/python_string/

我想演示使用 + 连接字符串确实比使用 "".join(...) 慢。但不知何故我失败了:

%%timeit
result = ""
for i in range(3000000):
result = result + 100 * str(i)

3.28 s ± 46.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

还有

%%timeit
result = []

for i in range(3000000):
result.append(100 * str(i))

result = "".join(result)

4.34 s ± 116 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

我使用的是Python 3.6,我的假设是最近的版本优化了字符串添加。对此有何评论?

最佳答案

问题在于你的比较不公平。特别是在第二个片段中,您还错误地计时了要连接的字符串的创建时间。附加可能会在那里占主导地位。

首先我们创建要连接的元素。

strings = []

for i in range(3000000):
strings.append(100 * str(i))

定时字符串连接

%%timeit
result = ''
for i in strings:
result = result + i

1.65 s ± 23.3 ms per loop

现在为 join 方法计时

%timeit result = ''.join(strings)

571 ms ± 10.3 ms per loop

因此,连接比连接更快的说法成立!

关于python - Python 中的字符串加法真的比使用 join 慢吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com