I was doing some analysis for doing list
concatenation using two different approaches for varying lengths of lists, with different Python versions.
Using +=
in 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
Using +=
in 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
Using extend
in Python 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
Using extend
in Python 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
- I'm surprised to notice that Python 3 is much slower than Python 2, and the jump is huge.
- Another quite interesting thing is doing
+=
is much more faster than doing anextend
.
Any implementation reasons to justify the above observations, especially between Python 2 & Python 3?