Tr[list]
as well as Total[list]
(which Gianluca Gorni mentioned) sum a list, and quickly if list
is a packed array. Plus @@ list
unpacks the list first. If list
is not packed, then the three have similar performance. If the list can be packed, then Total[Developer`ToPackedArray@list]
is faster than Total[list]
. And list . ConstantArray[1, Length@list]
is often fastest, except for the amount of typing. FromDigits[list, 1]
is an arcane way to sum a list, but it's faster than Plus @@ list
.
I do not know of a similar function for products. WRI has introduced variants for a thousand operations, but not for this fairly common one. Tr[list, Times]
forms the product, but not as efficiently as it sums a list. On large packed arrays, Fold[Times, list]
is about twice as fast as Times @@ list
or Tr[list, Times]
.
That said — and ignore the arcana — I often see users using Sum[]
to add up some numbers. Sum[]
is, to my mind, principally a symbolic summation tool. It will do symbolic analysis first to determine a summation method. If it chooses something other than Method -> "Procedural"
, it will probably do more symbolic analysis, which is usually slow compared to machine float/int operations. Here is an example:
Sum[2. i, {i, 10^6}] // RepeatedTiming
Sum[2. i, {i, 10^6}, Method -> "Procedural"] // RepeatedTiming
Total[2. Range[10^6]] // RepeatedTiming
(*
{0.176149, 1.*10^12}
{0.0119958, 1.*10^12}
{0.000709462, 1.*10^12}
*)
While it is nice to have an efficient Total[]
(or Tr[]
), it would be nicer if Sum[]
did all summation tasks, including this. Ditto for Product[]
. Your one-argument suggestions are worth considering.