Skip to content

Instantly share code, notes, and snippets.

@juanarrivillaga
Last active April 1, 2019 23:19
Show Gist options
  • Save juanarrivillaga/d7cdf5e72fbe2db80ef342aa7d7437af to your computer and use it in GitHub Desktop.
Save juanarrivillaga/d7cdf5e72fbe2db80ef342aa7d7437af to your computer and use it in GitHub Desktop.
import pandas as pd
import matplotlib.pyplot as plt
import time
def filter_items_newlist(items, item):
return [x for x in items if x != item]
def filter_items_inplace_gen(items, item):
items[:] = (x for x in items if x != item)
def filter_items_inplace(items, item):
ix_dst = 0
for ix_src, x in enumerate(items):
if x != item:
items[ix_dst] = x
ix_dst += 1
del items[ix_dst:]
def time_func(N, f):
items = list(range(N))
start = time.perf_counter()
f(items, N)
stop = time.perf_counter()
return stop - start
NS = range(0, 1_000_000, 10_000)
inplc = [time_func(n, filter_items_inplace) for n in NS]
inplc_gen = [time_func(n, filter_items_inplace_gen) for n in NS]
new = [time_func(n, filter_items_newlist) for n in NS]
df = pd.DataFrame({"in-place":inplc, "in-place-gen": inplc_gen, "new-list":new}, index=NS)
df.plot()
plt.savefig('in-place-vs-new-list-filter.png')
@juanarrivillaga
Copy link
Author

juanarrivillaga commented Apr 1, 2019

in-place-vs-new-list-filter

Note, this is really the best-case difference for the in-place algorithm, since nothing is actually removed, since N is never in the list!

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