Actually I don't understand why your solution is faster, since myArray["NonzeroValues"] creates a list just like ArrayRules[myArray] does.
Mathematica employs the copy-on-write paradigm. When we do
a = Range[10000];
it does indeed allocate memory for 10000 elements. But when we do
b = a;
it does not allocate memory for a further 10000 elements. b
and a
will point to the same area of memory.
Conceptually, a
and b
are two entirely separate variables. But the system will take the opportunity to share storage between them when possible.
Now if we change b
using
b[[1]] = 42;
then a
and b
won't have the same value anymore, and won't be able to share storage. Only at this pointi.e. when changing b
will Mathematica allocate separate storage for b
.
It's also interesting to read up on the Share[]
command, which will attempt to detect duplicate data and share their storage to conserve memory.
Most of this sharing is fully transparent to the user. We do not need to be aware of it to get correct results. But it is useful to know about it when we want to write efficient programs.