Optimizations (was Re: reduce vs. for loop)

Just van Rossum just at xs4all.nl
Tue Mar 26 10:22:03 EST 2002


In article <a7q2nf$31b$1 at panix1.panix.com>, aahz at pythoncraft.com (Aahz) 
wrote:

> >Just out curiosity, 
> >why is fact2 a bit faster than fact1?
> >
> >def fact1(n):
> >    return reduce (operator.mul, range(1L,n + 1))
> >
> >def fact2(n):
> >    result = n * 1L
> >    for i in range(1 , n):
> >        result *= i
> >    return result
> 
> Try this:
> 
> def fact3(n):
>     mul = operator.mul
>     return reduce(mul, range(1L, n+1) )

operator.mul will be evaluated only once in even in fact1, so this 
shouldn't make any difference.

Just



More information about the Python-list mailing list