Why is map() preferable in this case?
steven.bethard at gmail.com
Tue Sep 20 00:52:11 CEST 2005
Delaney, Timothy (Tim) wrote:
> Devan L wrote:
>>Map is in C. It's faster, but not as clear. Some people do think
>>map(f, L) is nicer though. Google is your friend here, if you want to
>>read the old arguments.
> map() will be faster if the function you are calling from map() is
> *also* in coded in C. If it's coded in python, then the generator
> expression will probably be faster.
> Use whatever reads better to you. Look at optimising when you need to,
> and not before.
While I fully agree with your conclusion, I don't think it's right to
say that a Python-coded function in a list comprehension will be faster
than the corresponding map. Consider:
> python -m timeit -s "r = xrange(1000); f = lambda x: 10*x" "map(f, r)"
1000 loops, best of 3: 707 usec per loop
> python -m timeit -s "r = xrange(1000); f = lambda x: 10*x" "[f(i) for
i in r]"
1000 loops, best of 3: 749 usec per loop
However, when a list comprehension allows you to inline a function, it's
almost certainly going to be faster:
C:\Documents and Settings\steve>python -m timeit -s "r = xrange(1000)"
"[10*i for i in r]"
1000 loops, best of 3: 300 usec per loop
More information about the Python-list