Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why lambda function in list comprehension is slower than in map?

Tags:

python

lambda

I made a test

%timeit list(map(lambda x:x,range(100000)))
%timeit [(lambda x:x)(i) for i in range(100000)]

gives

29 ms ± 4.4 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
51.2 ms ± 3.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Why in python lambda function is slower in list comprehension than in map?

like image 538
user15964 Avatar asked Jan 25 '23 09:01

user15964


1 Answers

Because in your first code snippet the lambda is created only once and executed 100000 times while on the second it is created and executed in every iteration.

To be honest I am surprised that the difference is not even bigger but your two timings should grow further apart the largest the length of the iterable is.


As a sidenote, notice that even if you change the lambda to a built-in function that does not have to be created first but rather only looked-up, you still get the same trend:

> py -m timeit "list(map(float, range(10000)))"
200 loops, best of 5: 1.78 msec per loop

> py -m timeit "[float(x) for x in range(10000)]"
100 loops, best of 5: 2.35 msec per loop

An improvement can be achieved by binding the function to a variable, but the list(map()) scheme is still faster.

> py -m timeit "r=float;[r(x) for x in range(10000)]"
100 loops, best of 5: 1.93 msec per loop

As to why the binding to a local variable is faster, you can find more information here.

like image 77
Ma0 Avatar answered Jan 30 '23 23:01

Ma0