[Metakit] Performance comparison Q
Magnus Lie Hetland
magnus at hetland.org
Mon May 9 22:35:58 CEST 2005
Brian Kelley <fustigator at gmail.com>:
>
> You can always use reduce which operators on a function of two parameters
>
> def f(a,b):
> if b%7>3: return a+b
> return a
>
> data = range(10)
> print reduce(f, data)
I did a little test of this as opposed to using the function in an
ordinary while loop, and got a speedup factor of about 1.2 (with the
reduce version beeing faster). You don't get that much of a speedup
using reduce unless you're reducing with a built-in operator.
[snip]
> which will not make a temporary list. Generators are essentially
> co-routines that act like iterators. Co-routines can yield execution
> until the next element in the iterator is requested. Using sum
> instead of reduce(operator.add... will still be faster)
Yup. sum() is good. And, as far as I know, Guido is thinking about
adding more functions like it (e.g., product) mainly to get people to
stop using reduce() :)
It's mainly a matter of readability, I guess.
If you're looking for typical, plain-vanilla Python loops, the
for-loop is more "pythonic" than reduce(), IMO. (If you run it with
psyco you might not even get a speedup with reduce at all.)
Just a penny's worth or so... ;)
--
Magnus Lie Hetland Fall seven times, stand up eight
http://hetland.org [Japanese proverb]
More information about the Metakit
mailing list