I have two pieces of code that do exactly the same thing. However, the memory consumption is very different in the two approaches, and I cannot figure out the reason.
Here is the code:
nMax = 10
attemptOne = Sum[ Total @ i , {i , Subsets[Range @ nMax, {4}]}];
attemptTwo = Sum[Total[{i , j , k , l}], {l, 4, nMax}, {k, 3, l - 1}, {j, 2, k - 1}, {i, 1, j - 1}]
When I check the memory consumption the difference is huge:
In[11]:= MaxMemoryUsed[
Sum[ Total @ i , {i , Subsets[Range @ nMax, {4}]}]]
Out[11]= 17864
In[12]:= MaxMemoryUsed[
Sum[Total[{i , j , k , l}], {l, 4, nMax}, {k, 3, l - 1}, {j, 2,
k - 1}, {i, 1, j - 1}]]
Out[12]= 1192
Can anybody explain this behavior? I would like to write my code using an approach like attemptOne
, since this is easy to generalize to sublists of length different from 4.
UPDATE: probably the reason is simply that in attemptOne
the code first generates all the subsets and then does the evaluation. So it stores all the tuples in memory, while in the second approach it creates one tuple at a time and saves memory.
Can somebody confirm that my intuition is correct?