# Different timing with large array assignment

Consider the following example

n = 10^8;
AbsoluteTiming[
A = ConstantArray[1., n]; // anyFunc;
A[[2 ;; ;; 2]] = -1.;
]


{0.388108, Null}

n = 10^8;
AbsoluteTiming[
B = ConstantArray[1., n];
B[[2 ;; ;; 2]] = -1.;
]


{0.738504, Null}

A == B


True

Why is the first approach faster? The only difference is, there is an arbitrary function outside the first one. I am using Mathematica 12 on windows 10 64 bit.

• Set $HistoryLength=0 – ciao Nov 28, 2019 at 10:51 • @ciao Wow, that does help, but I wonder why it does so. Can you explain that. It is not like DownValues[Out] were totally cluttered... Nov 28, 2019 at 11:41 • @HenrikSchumacher I'd bet that the history tracking of the kernel keeps a reference to B but not A that causes the tensor to be copied when some elements are changed to -1. That the tracking would be turned off when one sets $HistoryLength = 0 makes sense; but why a reference to B exists but not to A -- or why a reference to B exists at all -- I cannot explain. Nov 28, 2019 at 14:33
• @HenrikSchumacher: I have no idea, and the days of being motivated to dig way under the weighted covers to find out have faded. I found this and similar behaviors years ago, as did others, but the how/why of this particular case... beats me. Perhaps a Wolfram engineer might chime in.
– ciao
Nov 28, 2019 at 17:27
• This \$HistoryLength = 0 can be relevant in wolframscript, cause there you cannot have access to history even though is set to infinity by default. It would make sense to set it to zero if it gives performance increase. Dec 1, 2019 at 17:55