# Does Share have any side effect?

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

-

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:

MemoryInUse[]
=> 52558032


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

Share[]
=> 9857528

MemoryInUse[]
42921264


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.

-
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