在 Python 2 & Python 3 中使用“+=”与 "extend" 进行列表连接

List concatenation using "+=" vs "extend" in Python 2 & Python 3

我正在做一些分析,以使用两种不同的方法对不同长度的列表进行 list 连接,具有不同的 Python 版本。

Python 中使用 += 2:

$ python -m timeit -s "li1=range(10**4); li2=range(10**4)" "li1 += li2"  
10000 loops, best of 3: 55.3 usec per loop  
$ python -m timeit -s "li1=range(10**6); li2=range(10**6)" "li1 += li2"  
100 loops, best of 3: 9.81 msec per loop  

Python 中使用 += 3:

$ python3 -m timeit -s "li1=list(range(10**4)); li2=list(range(10**4))" "`li1 += li2`"  
10000 loops, best of 3: 60 usec per loop  
$ python3 -m timeit -s "li1=list(range(10**6)); li2=list(range(10**6))" "`li1 += li2`"  
100 loops, best of 3: 11 msec per loop  

Python 中使用 extend 2:

$ python -m timeit -s "li1=range(10**4); li2=range(10**4)" "li1.extend(li2)"  
10000 loops, best of 3: 59 usec per loop  
$ python -m timeit -s "li1=range(10**6); li2=range(10**6)" "li1.extend(li2)"  
100 loops, best of 3: 10.3 msec per loop  

Python中使用extend 3:

$ python3 -m timeit -s "li1=list(range(10**4)); li2=list(range(10**4))" "li1.extend(li2)"  
10000 loops, best of 3: 64.1 usec per loop  
$ python3 -m timeit -s "li1=list(range(10**6)); li2=list(range(10**6))" "li1.extend(li2)"  
100 loops, best of 3: 11.3 msec per loop  
  1. 我很惊讶地发现 Python 3 比 Python 2 慢很多,而且跳跃很大。
  2. 另一件非常有趣的事情是 +=extend 快得多。

任何实施原因 来证明上述观察结果,尤其是在 Python 2 和 Python 3 之间?

I'm surprised to notice that Python 3 is much slower than Python 2, and the jump is huge.

正如其他人所指出的,您的基准测试不支持您关于 Python 3 比 慢得多 的说法。 9.81 毫秒对 11 毫秒,10.3 毫秒对 11.3 毫秒?

据记载,Python 3 比 Python 2 慢一点。What's new document 性能说明:

The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There’s room for improvement, but it will happen after 3.0 is released!


Another quite interesting thing is doing += is much more faster than doing an extend.

同样,"much [more] faster" 被夸大了。 9.81 毫秒与 10.3 毫秒?

答案参见this related SO questionextend 需要 Python 级别的函数调用,而 += 可以在 C 级别进行优化,因此速度稍快。