map versus the 'for' loop

Tim Peters tim_one at email.msn.com
Sat Dec 4 17:12:17 EST 1999


[Ionel Simionescu]
> In some situations, the use of map() can speed up things, which would
> normally be done in a loop.
>
> --- e.g.
>
> # <map>
> y = map(func, x)
>
> # vs.
>
> # <for loop>
> y = [None]* len(x)
> for k in range(x): y[k] = func(x[k])
>
> ---
>
> I hereby ask those with knowledge about the interpreter's
> internals what the trade-offs/cavets are.

If func is None, map is much faster.

If func is a Python function, map saves only loop overhead, and is a minor
gain (typically no more than a few percent).

If func is some builtin operation (like "+" or "len") spelled at least
roughly the same way in both cases, it depends on the precise operation, but
map will usually be significantly faster (it again saves only loop overhead,
but when the operation is implemented in C the loop overhead is a much
bigger relative burden).

The funny ones are where someone takes a perfectly fine Python loop like:

    for i in xrange(len(x)):
        z[i] = x[i] * y[i]

and converts it to a lambda-slinging map:

    z = map(lambda a, b: a*b, x, y)

under the assumption that "map must be faster".  map is significantly slower
if you have to *introduce* a lambda (or any other spelling of a Python
function) to get it to work (you've then added the expense of a Python-level
function call to each result computed, that the explicit Python loop
avoided).

> The speed gain brought by map() might have a cost (e.g. space)
> that I'm not aware of, and which could bite in certain situations.

Not in general.  If you restrict your use of map to cases where it improves
*clarity*, you'll rarely go wrong.

provided-i'm-the-sole-judge-of-clarity<wink>-ly y'rs  - tim






More information about the Python-list mailing list