Skip to content

Instantly share code, notes, and snippets.

@Coldsp33d
Last active December 5, 2020 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Coldsp33d/0a0e0e0eee8377489aed01358fe33a47 to your computer and use it in GitHub Desktop.
Save Coldsp33d/0a0e0e0eee8377489aed01358fe33a47 to your computer and use it in GitHub Desktop.
Concatenate 2 (or more) lists - Benchmarking
from itertools import chain
import perfplot
import numpy
def add(L):
x, y = L
return x.copy() + y
def chain_(L):
x, y = L
return list(chain(x.copy(), y))
def unpacking(L):
x, y = L
return [*x.copy(), *y]
def extend(L):
x, y = L
x = x.copy()
x.extend(y)
return x
def iadd(L):
x, y = L
x = x.copy()
x += y
return x
# plot 1
perfplot.show(
setup=lambda n: [np.random.choice(100, n).tolist()] * 2,
kernels=[add, chain_, unpacking, extend, iadd],
labels=['a + b', 'list(chain(a, b))', '[*a, *b]', 'a.extend(b)', 'a += b'],
n_range=[2**k for k in range(0, 20)],
xlabel='len(a)',
logx=True,
logy=True)
# plot 2
perfplot.show(
setup=lambda n: [np.random.choice(100, 100).tolist()] * n,
kernels=[
lambda L: sum(L, []),
lambda L: list(chain.from_iterable(L))
],
labels=['sum', 'chain'],
n_range=range(1, 1000, 50),
xlabel='# lists',
logy=True,
logx=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment