Skip to content

Instantly share code, notes, and snippets.

@mekarpeles
Created August 20, 2012 21:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mekarpeles/3408081 to your computer and use it in GitHub Desktop.
Save mekarpeles/3408081 to your computer and use it in GitHub Desktop.
Python 2.7 Performance Comparison: list concatenation (+) vs list.extend()
mek@bigbertha:~/7-Projects$ python
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> def test():
... """Comapring concat. + vs list.extend"""
... x = range(10000000)
... y = range(10000000)
... x0 = time.clock()
... z = x + y
... t1 = time.clock() - x0
... x1 = time.clock()
... x.extend(y)
... t2 = time.clock() - x1
... print "+ takes %s, extend takes %s" % (t1, t2)
...
>>> test()
+ takes 0.31, extend takes 0.12
@nik312123
Copy link

nik312123 commented Oct 7, 2018

I can confirm these results: https://pastebin.com/rYbfXQDp

My averages after running this program five times are the following:

Concat average: 2.711305618286133e-07
Extend average: 2.4134492874145505e-07

Concat average: 2.803680896759033e-07
Extend average: 2.349388599395752e-07

Concat average: 3.220231533050537e-07
Extend average: 2.413630485534668e-07

Concat average: 2.821462154388428e-07
Extend average: 2.3563313484191895e-07

Concat average: 2.739343643188477e-07
Extend average: 2.407205104827881e-07

In all cases, extend beat concat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment