Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `extend` faster than `+=`?

In python, we can concatenate lists in two ways:

  1. lst.extend(another_lst)
  2. lst += another_lst

I thought extend would be faster than using +=, because it reuses the list instead of creating a new one using the other two.

But when I test it out with timeit, it turns out that += is faster,

>>> timeit('l.extend(x)', 'l = range(10); x = range(10)')
0.16929602623
>>> timeit('l += x', 'l = range(10); x = range(10)')
0.15030503273
>>> timeit('l.extend(x)', 'l = range(500); x = range(100)')
0.805264949799
>>> timeit('l += x', 'l = range(500); x = range(100)')
0.750471830368

Is there something wrong with the code I put in timeit?

like image 845
satoru Avatar asked Nov 14 '10 09:11

satoru


1 Answers

EDIT: I've tested the performance and I can't replicate the differences to any significant level.


Here's the bytecode -- thanks to @John Machin for pointing out inconsistencies.

>>> import dis
>>> l = [1,2,3]
>>> m = [4,5,6]
>>> def f1(l, m):
...     l.extend(m)
...
>>> def f2(l,m):
...     l += m
...
>>> dis.dis(f1)
  2           0 LOAD_FAST                0 (l)
              3 LOAD_ATTR                0 (extend)
              6 LOAD_FAST                1 (m)
              9 CALL_FUNCTION            1
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE
>>> dis.dis(f2)
  2           0 LOAD_FAST                0 (l)
              3 LOAD_FAST                1 (m)
              6 INPLACE_ADD
              7 STORE_FAST               0 (l)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

Notice that extend uses a CALL_FUNCTION instead of an INPLACE_ADD. Any trivial performance differences can probably be put down to this.

like image 71
Katriel Avatar answered Nov 15 '22 19:11

Katriel