# Does Sum calculate all terms before summing them?

After calculating the sum of a large number of large objects, using

B = Sum[RandomInteger[{0, 1}, {10^6}], {100}];


I find that MaxMemoryUsed[] has increased by 400MB, which is about 100 times ByteCount[B]. This seems to mean that Mathematica has calculated all terms in the sum before adding them up (equivalent to Plus@@Table[...]), rather than keeping a running total. Is this correct?

Because of memory constraints, I need to calculate the sum using a running total. I can obviously do it procedurally (Do[B+=..., {10^2}]), but is there a better way?

And, just out of interest, why does Mathematica do it this way? It's not obvious that it's ever significantly more (time) efficient, and in some cases it will be much less (memory) efficient.

• Look at your code, it completes the inner function first. Loops are pretty minimalistic, since it's c language. I doubt there's a faster way. – Feyre Jul 3 '15 at 9:21
• Sum is a very complex function that will try to be smart and use the best method for the situation. This can be symbolic, or dumb sequential summation, etc. If you need precise control over how to do it, don't use Sum. For you particular use case I'd never use Sum, which is really meant for symbolic calculations. I'd use Total or Apply[Plus] if memory is not an issue and I'd use a procedural accumulation (Do) if it is an issue. Some might prefer something like Nest as an alternative to Do. – Szabolcs Jul 3 '15 at 9:24
• To answer the question in the title: with the setting Method -> "Procedural", yes. Otherwise, it tries a number of clever symbolic manipulations depending on the form of the summand. In your case, you are hammering nails with a screwdriver. Use Total[], as suggested in previous comments. – J. M. will be back soon Jul 3 '15 at 9:32
• RandomVariate[BinomialDistribution[100, 1/2], 1*^6] accomplishes same thing as your sum. Also, avoid uppercase initials in your symbols, might clash with built-ins. – ciao Jul 3 '15 at 10:23
• Thanks, @ciao, but the code above is a minimal example, not the case I'm actually interested in. – Stephen Powell Jul 3 '15 at 10:27