reduce vs. for loop

Andy Gimblett gimbo at ftech.net
Tue Mar 26 05:43:04 EST 2002


On Tue, Mar 26, 2002 at 08:29:36AM +0100, m2 at plusseven.com 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

Function call overhead in Python is bigger than for loop overhead.

That sentence is taken from this page, which you might find
interesting:

    http://www.python.org/doc/essays/list2str.html

HTH,

Andy

-- 
Andy Gimblett - Programmer - Frontier Internet Services Limited
Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/
Statements made are at all times subject to Frontier's Terms and
Conditions of Business, which are available upon request.




More information about the Python-list mailing list