Consider the following example

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

{0.388108, Null}

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

{0.738504, Null}

A == B


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.

  • 4
    $\begingroup$ Set $HistoryLength=0 $\endgroup$
    – ciao
    Nov 28, 2019 at 10:51
  • $\begingroup$ @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... $\endgroup$ Nov 28, 2019 at 11:41
  • 3
    $\begingroup$ @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. $\endgroup$
    – Michael E2
    Nov 28, 2019 at 14:33
  • 1
    $\begingroup$ @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. $\endgroup$
    – ciao
    Nov 28, 2019 at 17:27
  • $\begingroup$ 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. $\endgroup$
    – Fortsaint
    Dec 1, 2019 at 17:55


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.