If we want to save some outputs of the function, we often use the memoization pattern as follows,


If I call this function many times for different arguments, Mathematica has to first find the best pattern defined so far i.e., choose the right overload. Is there any performance guarantee if there are $N$ overloaded functions in terms time complexity? As we now have Association, we have another natural way to memoize even though using Association looks uglier. I also want to know which way is more efficient given that there are $N$ overloaded functions with the same name.

  • 1
    $\begingroup$ This question seems to suggest that Association has constant access time so my belief (without any further research or justification) is that Association would be the fastest for even moderately sized $N$. $\endgroup$
    – IPoiler
    Commented Sep 24, 2015 at 18:55
  • $\begingroup$ @It'sPronouncedOiler Thanks, I am a ware of that thread. Association certainly provides attractive time complexity however in terms of usability, I still think the conventional memoization pattern is more readable and easier. So, if the conventional way is still reasonably fast, I would like to stick to using it. That's the whole point of my question. $\endgroup$
    – Sungmin
    Commented Sep 24, 2015 at 19:11
  • 3
    $\begingroup$ The complexity is quasi-constant time for both DownValues and Association. For non-pattern arguments, DownValues store results in a hash-table. If the number of entries becomes really large, you may notice that lookup becomes slower, but it should not be more than a factor of 2 or so, for realistic number of entries. As for ugliness, here I have suggested a solution based on pure functions, which might be ok, and has additional advantage over DownValues-based method: automatic garbage collection. $\endgroup$ Commented Sep 24, 2015 at 20:14


Your Answer

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

Browse other questions tagged or ask your own question.