1
$\begingroup$

For my current program in Mathematica, sometimes I will encounter an error regarding \$IterationLimit and \$RecursionLimit. So I always set these two numbers to very large at the starting of every notebook. Till now, I didn't find any problem.

I want to understand what's the disadvantage of using a huge \$RecursionLimit or \$IterationLimit? By doing this way will I make the code slower or consume more memory?

For other languages, I heard this is related to the stack of evaluations. But I have no idea how memory is manipulated for Mathematica for this aspect.

Apparently, if there is no disadvantage Mathematica should always set these two numbers to Infinity.

$\endgroup$
5
  • 7
    $\begingroup$ Would it not be better to modify/fix your algorithm so to not to encounter $IterationLimit and $RecursionLimit in first place than worry about how to increase them? I do not think I've hit IterationLimit myself, but did with RecursionLimit number of times, and always this was due to a bug in my code. Without a limit, then Mathematica will most likely end up using all the memory it can or worst go into an infinite loop and you have to kill the process from outside. That is why they set this limit internally. $\endgroup$
    – Nasser
    May 10, 2022 at 12:57
  • 2
    $\begingroup$ Welcome to the Mathematica Stack Exchange. The word limit suggests that this is a value that should never be reached inadvertently. That the user is nearing that limit is often, but not always, indicative of a looming crash. Could you please add an example to make a more concrete case for the counter argument? $\endgroup$
    – Syed
    May 10, 2022 at 14:49
  • 6
    $\begingroup$ Setting $RecursionLimit high risks crashing the kernel from subroutine stack exhaustion. And setting either high has a way of masking code bugs. Hence the mid-range default values. $\endgroup$ May 10, 2022 at 15:57
  • $\begingroup$ Thanks for the comment. Generally, a too deep recursive code is not considered to be well written, especially in Mathematica. I don't have a very solid example at my hand, so I'm asking for the possible risk. It seems the worst risk is running out of the stack and the kernel crash. But it won't spend more memory than it should be. $\endgroup$
    – Canonical
    May 10, 2022 at 19:37
  • 1
    $\begingroup$ I'd say the biggest risk is probably spending too much time (due to setting infinite limits) in testing code I need to improve. That's wasting my time, and to me, that's a real waste. If the kernel crashes, and it takes a long time to recompute some data, then that is a waste of my time, too. One can save such data in a LocalObject, though, and avoid the risk. Thirdly, high recursion pushing large amounts of data onto a stack could result in swapping, which would waste my time, if refactoring the code could eliminate swapping. — Another point of view: a kernel crash could annoy a client. $\endgroup$
    – Michael E2
    May 11, 2022 at 16:44

0