Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

According to the documentation,

Share[expr] changes the way expr is stored internally, to try and minimize the amount of memory used.

How should I then interpret the fact that x1 != x2 + x3 after running the following code?

e = Table[j (x + i), {i, 5}, {j, i}];
x1 = ByteCount@e
x2 = Share[e]
x3 = ByteCount@e
share|improve this question
up vote 3 down vote accepted

Well, I give it a try to answer your question.

The way Share works is, that all symbols in the symbol table are checked, and those with the same values are cross-referenced. So you can not expect that your e is reduced but if there is another e (say e2) with exact the same value, it will get cross referenced.

Let's check this assumption. The Integral of x^66 Sin[x]^44 takes about ~500MB:

ByteCount[tmp1 = Integrate[x^35 Sin[x]^44, x]]
=> 506960

To get the size of the Mathematica subexpression we can use LeafCount:

LeafCount[tmp2 = Integrate[x^35 Sin[x]^44, x]]
=> 13076

Now tmp1 and tmp2 do have exactly the same value. Let's check the memory in use:

=> 52558032

If we call now Share there should be a considerable amount of reduced memory consumption:

=> 9857528


If we subtract these values, we may expect that we see the reduction of (tmp1 + tmp2) into one tmp for instance. The problem is we don't since MemoryInUse[] does involve state changes and so it is nearly impossible to get a discrete state.

If we try to call Share on tmp2 we will realise, that Share is not able to save any memory for tmp2, since it is already cross-referenced with tmp1.

This is how Share[] basically works.

Hope this helps.

share|improve this answer
I understand what you wrote, what bothers me is the statement in the documentation "Share returns the number of bytes freed as a result of sharing …" x2 of the original question is not zero, so where did those savings go? – Hector Nov 15 '13 at 20:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.