You are on page 1of 1

@Aaron Hall One small comment in algorithm for timing.

"extend_one" may return


"slightly wrong" time because the creation of a list is also involved. Probably
better is to create the items as variables (ex1 = 0 and ex2 = [0]) and pass these
variables, if you want to be more strict. – ilias iliadis Mar 31 '18 at 18:06
11
Perfect answer indeed. What about performance of l1 += l2 vs l1.extend(l2)? – Jean-
Francois T. Apr 23 '18 at 3:54
2
@Jean-FrancoisT.: l1 += l2 and l1.extend(l2) ultimately execute the same code (the
list_extend function in listobject.c). The only differences are: 1. += reassigns l1
(to itself for lists, but the reassignment supports immutable types that aren't the
same object after), which makes it illegal if l1 is actually an attribute of an
immutable object; for example, t = ([],), t[0] += lst would fail, while
t[0].extend(lst) would work. 2. l1 += l2 uses dedicated bytecodes, while
l1.extend(l2) uses generalized method dispatch; this makes += faster than extend. –
ShadowRanger Aug 17 '18 at 19:10
2
The fact that += must reassign l1 does mean that in some cases, the slower dispatch
of extend is partially or wholly made up for by not assigning back to the left hand
side. For example, if the list is an attribute of an object, self.l1 += l2 and
self.l1.extend(l2) have identical performance on my Python 3.6 install, simply
because real operation is more like self.l1 = self.l1.__iadd__(l2), which means it
must perform a moderately expensive STORE_ATTR that self.l1.extend(l2) doesn't have
to. – ShadowRanger Aug 17 '18 at 19:20
1
Simple comparison in local tests: For a local variable (so the += is just using
STORE_FAST, which is super cheap), where the value being added is an existing list
with one item in it, with the operation repeated 1000 times, += took about 33 ns on
average, while extend took 78 ns, a difference of 45 ns. If l1 is a global
(requires more expensive STORE_GLOBAL), the difference narrows to 17 ns. If l1 is
actually local.l1 (requires even more expensive STORE_ATTR), there is no meaningful
difference between += and extend (timings roughly identical; extend sometimes
wins). – ShadowRanger Aug 17 '18 at 19:32

You might also like