I am wondering if the sum() builtin has an andventage over a long addition ?
is
sum(filter(None, [a, b, c, d]))
faster than
a + b + c + d
assuming I am using CPython ?
thanks
EDIT: What if those variables are Decimals ?
A quick example (note that, to try to be fairer, the sum
version takes a tuple
argument, so you don't include the time for building that structure (a, b, c, d)
, and doesn't include the unnecessary filter
):
>>> import timeit
>>> def add_up(a, b, c, d):
return a + b + c + d
>>> def sum_up(t):
return sum(t)
>>> t = (1, 2, 3, 4)
>>> timeit.timeit("add_up(1, 2, 3, 4)", setup="from __main__ import sum_up, add_up, t")
0.2710826617188786
>>> timeit.timeit("sum_up(t)", setup="from __main__ import sum_up, add_up, t")
0.3691424539089212
This is pretty much inevitable - add_up
doesn't have any function call overhead, it just does 3 binary adds. But the different forms have different uses - sum
doesn't care how many items are given to it, whereas you have to write each name out with +
. In an example with a fixed number of items, where speed is crucial, +
has the edge, but for almost all general cases sum
is the way to go.
With Decimal
s:
>>> t = tuple(map(Decimal, t))
>>> a = Decimal(1)
>>> b = Decimal(2)
>>> c = Decimal(3)
>>> d = Decimal(4)
>>> timeit.timeit("add_up(a, b, c, d)", setup="from __main__ import sum_up, add_up, t, a, b, c, d")
0.5005962150420373
>>> timeit.timeit("sum_up(t)", setup="from __main__ import sum_up, add_up, t, a, b, c, d")
0.7599533142681025