Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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.from_iterable'],
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
You can’t perform that action at this time.