列表连接真的比python中的字符串连接快吗? [英] Is list join really faster than string concatenation in python?
问题描述
我发现字符串连接似乎比列表连接具有更少的python字节码。
I find that string concatenation seems to have less python bytecode than list join.
这是一个示例。
test.py:
a = ''.join(['a', 'b', 'c'])
b = 'a' + 'b' + 'c'
然后我执行 python -m dis test.py
。
我得到以下python字节码(python 2.7):
Then I execute python -m dis test.py
.
I got the following python bytecode (python 2.7):
1 0 LOAD_CONST 0 ('')
3 LOAD_ATTR 0 (join)
6 LOAD_CONST 1 ('a')
9 LOAD_CONST 2 ('b')
12 LOAD_CONST 3 ('c')
15 BUILD_LIST 3
18 CALL_FUNCTION 1
21 STORE_NAME 1 (a)
3 24 LOAD_CONST 6 ('abc')
27 STORE_NAME 2 (b)
30 LOAD_CONST 4 (None)
33 RETURN_VALUE
很明显,字符串连接的字节码数量较少,只加载了字符串'abc'
直接。
Obviously, the bytecode number of string concatenation is less.It just load string 'abc'
directly.
有人可以解释为什么我们总是说列表联接要好得多吗?
Can anyone explain why we always say that list join is much better?
推荐答案
方法1
:'a'+'b'+'c'
Method 1
: 'a' + 'b' + 'c'
方法6
:a ='' .join(['a','b','c'])
Method 6
: a = ''.join(['a', 'b', 'c'])
将20,000个整数连接成86kb长的字符串:
20,000 integers were concatenated into a string 86kb long :
Concatenations per second Process size (kB)
Method 1 3770 2424
Method 6 119,800 3000
结论:是, str.join()
比典型的串联( str1 + str2
)快得多。
Conclusion : YES, str.join()
is significantly faster then typical concatenation (str1+str2
).
这篇关于列表连接真的比python中的字符串连接快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!