sum() vs. loop
Chris Angelico
rosuav at gmail.com
Mon Oct 11 17:57:42 EDT 2021
On Tue, Oct 12, 2021 at 8:55 AM Steve Keller <keller.steve at gmx.de> wrote:
>
> I have found the sum() function to be much slower than to loop over the
> operands myself:
>
> def sum_products(seq1, seq2):
> return sum([a * b for a, b in zip(seq1, seq2)])
>
> def sum_products2(seq1, seq2):
> sum = 0
> for a, b in zip(seq1, seq2):
> sum += a * b
> return sum
>
> In a program I generate about 14 million pairs of sequences of ints each
> of length 15 which need to be summed. The first version with sum() needs
> 44 seconds while the second version runs in 37 seconds.
>
> Can someone explain this difference?
>
When you use sum, you're constructing a list. Try removing the square brackets:
return sum(a * b for a, b in zip(seq1, seq2))
It's also possible that the genexp has more overhead than simply
iterating directly, but at very least, this will reduce the memory
consumption.
ChrisA
More information about the Python-list
mailing list