5
$\begingroup$

Is there a reason to use Hold* attributes for functional code (e.g. no intention to mutate input)? I'd expect performance gains as in pass by value vs pass by reference.

E.g.

data = RandomReal[1, 10^8];

data // Function[x, x[[1]]] // RepeatedTiming
{8.*10^-7, 0.0372378}
data // Function[x, x[[1]], HoldAllComplete] // RepeatedTiming
{8.0*10^-7, 0.0372378}

The question is, why doesn't it matter? Or are there cases where it matters, performance tuning wise.

$\endgroup$
  • $\begingroup$ Good question. But I'm not entirely sure that your test is too meaningful... If I increase the size of data, I don't see any change in the timings. I've also tried to unpack the array and to use symbols with downvalues, without any clear influence on the result. $\endgroup$ – Lukas Lang Apr 10 at 15:12
  • $\begingroup$ For your information, Mathematica does not use the concepts of pass by value versus pass by reference. See question 156319 $\endgroup$ – Somos Apr 10 at 15:22
  • 1
    $\begingroup$ @LukasLang I appreciate better examples, this was the simplest that came to my mind. $\endgroup$ – Kuba Apr 10 at 15:43
  • 1
    $\begingroup$ Also, I believe that there are times when using the Hold attribute prevents mathematica from copying data, which can be important when working with large datasets when there is a risk of running out of RAM or hitting the swap memory limit. However, I found it difficult to find good examples of this. $\endgroup$ – Sjoerd Smit Apr 10 at 15:44
  • 1
    $\begingroup$ @Somos I am not sure what concept it uses but if you write your code in a sloppy way 'copying' will make it slower. $\endgroup$ – Kuba Apr 10 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.