Which is faster?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Aug 30 02:01:05 EDT 2008


En Sat, 30 Aug 2008 01:26:35 -0300, cnb <circularfunc at yahoo.se> escribi�:

> For a big nbr of it might matter?
> Is av_grade O(n*2) and the first O(n)  when it comes to adding or is
> "sum x for x in y" just traversing the list ones, accumulating the
> values, it doesnt first build the list and then travese it for sum?

AFAIK both versions are O(n).
sum(x for x in y) contains a "generator expression" [1], it does not  
create an intermediate list.
sum([x for x in y]) contains a "list comprehension" [2] and it does create  
an intermediate list.

I'd say the version using sum() should be faster, because the iteration is  
implemented inside the interpreter, not in Python code as the other one.  
But you should actually measure their relative performance; use the timeit  
module for that.

> def averageGrade(self):
>         tot = 0
>         for review in self.reviews:
>             tot += review.grade
>         return tot / len(self.reviews)
>
> def av_grade(self):
>      return sum(review.grade for review in self.reviews) / \
>               len(self.reviews)

[1] http://docs.python.org/tut/node11.html#SECTION00111100000000000000000
[2] http://docs.python.org/tut/node7.html
-- 
Gabriel Genellina




More information about the Python-list mailing list