Speed: bytecode vz C API calls

Francis Avila francisgavila at yahoo.com
Wed Dec 10 17:19:59 EST 2003


Aahz wrote in message ...
>In article <tyfu148y6ye.fsf at pcepsft001.cern.ch>,
>Jacek Generowicz  <jacek.generowicz at cern.ch> wrote:
>>aahz at pythoncraft.com (Aahz) writes:
>>  http://www.python.org/doc/essays/list2str.html
>
>All right, what I should have said is that map() isn't enough faster
>than a for loop in the cases where it is faster to make much difference,
>and there are definitely cases where it's slower than the equivalent for
>loop, and it's usually less readable than some other way of getting
>speed.

That essay is a bit old, so not everything it says may still be true.

But in 2.3 at least, one case in which map is almost always much faster is
when the function used is a builtin.  In this case, map (which is also
builtin) calls the C function from C, and I'm pretty sure it gets this speed
by staying outside of the Python eval loop.  This can be wickedly fast (in
Python terms), and faster than list comps or for-loops with explicit list
appending, as a simple timeit will show.

For *Python* functions and lambdas (non-builtins), map can very often be
slower than a for-loop or list comprehension, for reasons not quite clear to
me.  And of course, where a for-loop or list comp can avoid calls
alltogether, it will always be faster than the equivalent function-using map
(unless map uses None as the function).

I think in the OP's case, any little drop of speed he can get more than
justifies the very, very slightly un-idiomatic use of map instead of a
for-loop.  Be warned that map() may go away in future Pythons, though....
--
Francis Avila





More information about the Python-list mailing list