While comparing various equivalent forms of filter(xs, lambda x: x != el) in Python, I stumbled upon something that surprised me. Consider the following forms:
def method1(xs, el):
p = lambda x: x != el
return [x for x in xs if p(x)]
def method2(xs, el):
return [x for x in xs if (lambda y: y != el)(x)]
I would expect that Python'd build the lambda only once, and then store it in a temporary variable, so that both forms perform about as well. Maybe even that method1 would perform worse due to the name lookup.
But when I benchmarked them, it turned out that method2 performed consistently worse than method1. Why is this? Is it rebuilding the lambda for every iteration?
My benchmark script (in a separate module, and expects methods to contain method1 and method2) is as follows:
import math, timeit
def bench(n,rho,z):
pre = """\
import random
from methods import %(method)s
x = [(random.randint(0,%(domain)i)) for r in xrange(%(size)i)]
el = x[0]\
"""
def testMethod(m):
mod = pre % { 'method': m, 'domain': int(math.ceil(n / rho)), 'size': n }
return timeit.timeit("%s(x, el)" % m, mod, number = z)/(z * n)
print "Testing", n, rho, z
return tuple(testMethod(m) for m in ("method1", "method2"))
n = 31
min_size, max_size = 10.0**1, 10.0**4
size_base = math.pow(max_size / min_size, 1.0/(n-1))
# size_default = 10**3
#min_sel, max_sel = 0.001, 1.0
#sel_base = math.pow(max_sel / min_sel, 1.0/(n-1))
sel_default = 0.001
tests = [bench(int(min_size*size_base**x), sel_default, 100) for x in xrange(n)]
#tests = [bench(size_default, min_sel*sel_base**x, 100) for x in xrange(n)]
def median(x):
x = list(sorted(x))
mi = int(len(x)/2)
if n % 2 == 0:
return x[mi]
else:
return (x[mi] + x[mi+1])/2
def madAndMedian(x):
meh = median(x)
return meh, median([abs(xx - meh) for xx in x])
for z in zip(*tests):
print madAndMedian(z)