Wolfram Language Paclet Repository
Community-contributed installable additions to the Wolfram Language
Functions for caching with automatic garbage collection
Contributed by: Jason Biggs, Wolfram Research
Functions for storing data in memory in a key-value store in such that the data is automatically deleted when there are no more references to the its key. These functions are intended for package developers who wish to take advantage of caching for expensive computations without the memory leaks associated with other techniques such as memoization and Once. A global weak cache is provided with functions for adding and retrieving data, and you can also create your own weak hash table that you control.
To install this paclet in your Wolfram Language environment,
evaluate this code:
PacletInstall["JasonB/WeakCache"]
To load the code after installation, evaluate this code:
Needs["JasonB`WeakCache`"]
Two expressions that are identical are considered SameQ:
In[1]:= | ![]() |
Out[3]= | ![]() |
However, they are different instances of the same data:
In[4]:= | ![]() |
Out[4]= | ![]() |
In[5]:= | ![]() |
Out[6]= | ![]() |
When an expression is used to store data in a weak cache it is stored under the objects physical memory address, rather than the contents of the expression:
In[7]:= | ![]() |
In[8]:= | ![]() |
Out[8]= | ![]() |
As in many examples for this paclet, we set the evaluation history to zero to avoid confusion:
In[9]:= | ![]() |
Out[9]= | ![]() |
Define an expression and set a cleanup function to be called when the expression goes out of scope:
In[10]:= | ![]() |
The expression is only evaluated when expr is cleared:
In[11]:= | ![]() |
Create a WeakHashTable for use in your package:
In[12]:= | ![]() |
Out[10]= | ![]() |
Create an expression and store some data in the table:
In[13]:= | ![]() |
Retrieve the data from the table:
In[14]:= | ![]() |
Out[14]= | ![]() |
Lookups are done by reference, not by value, so using an identical expression will return $Failed:
In[15]:= | ![]() |
Out[15]= | ![]() |
Assigning another variable to g will point to the same data:
In[16]:= | ![]() |
Out[8]= | ![]() |
When all references to the data are gone the cached data is cleared from the table:
In[17]:= | ![]() |
In[18]:= | ![]() |
Out[18]= | ![]() |
Wolfram Language Version 13.3