In[1] AA = RandomInteger[10, 1000000]; BB = AA;
In[2] Do[BB = AA;, 10000] // Timing
Out[2] {0., Null}
In[3] Do[BB[[77]] = i;, {i, 1, 10000}] // Timing
Out[3] {0., Null}
In[4] Do[BB[[i]] = i;, {i, 1, 10000}] // Timing
Out[4] {0., Null}
From Out[2], we see setting a variable to a large list takes no time.
From Out[3],Out[4], we see setting an element of a list to a number takes no time.
But
In[5] Do[BB = AA; BB[[77]] = i;, {i, 1, 10000}] // Timing
Out[5] {3.04688, Null}
alternately setting a variable to a large list + setting an element of a list to a number takes long time.
Q1) How can we explain it ?
Q2) In fact, mathematica reported it took 3.04688 seconds, but in fact it took about 20 seconds (physical watch) to get Out[5]. Personaly there have been some differences in the past, but this is the first time I've seen such a big difference.
BB=AA
is followed by a write accessBB[[77]]=i
, which triggers copy-on-write and which takes substantial amounts of time. $\endgroup$