Last active
December 5, 2020 22:18
-
-
Save Coldsp33d/0a0e0e0eee8377489aed01358fe33a47 to your computer and use it in GitHub Desktop.
Concatenate 2 (or more) lists - Benchmarking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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