# Memory management in Dynamic

Here is some example code for an image viewing aspect of a notebook I'm working on. I was hoping that the return value of LoadPage[] would be garbage collected when that slide was not visible anymore but that doesn't happen.

So for the concrete case I'm working on, I'm trying to figure out how to get this to use constant memory.

filenames =  FileNames[ "C:\\Pictures\\Camera Roll\\*.jpg"];

pages = Partition[filenames, 20];

LoadPage[page_] := Grid @ ArrayReshape[Import /@ pages[[page]], {4, 5}]

SlideView[
Dynamic[
Refresh[LoadPage[#], None]
] & /@ Table[i, {i, 1, Length[filenames]}]
, ImageSize -> Automatic
]


Memory usage from task manager while paging through a few pages.

I gather that basically I need to Clear[] that value, but I'm not sure how to assign a value for it (I tried a DynamicModule where I assigned to a var and cleared it, but I obviously did it incorrectly because it didn't free any memory). I also saw that Dynamic can take a Deinitialization function, but that seemed to only be called when the whole output SlideView in this case was deleted.

I guess the abstract problem I have is not knowing how to capture expr in Dynamic[expr], and even if I could capture that I'm not sure where I would put the Clear call such that it got called (presumably in the Refresh[], but only after advancing to the next slide).

• Looking at it more, I think I've realized the "leak" seems to be in the front-end. When I look at MemoryInUse it does stay pretty constant. But deleting the Out[x] frees the memory in the task manager. I tried setting HistoryLimit to 0 with no luck though. Still digging through other memory posts to see if I can find a solution (or workaround). – Dan Apr 26 '17 at 18:43
• Maybe MaintainDynamicCaches -> False or CacheGraphics->False would be of use, don't know how to use the former one though. – Kuba Apr 26 '17 at 19:02
• I figured out I could set the MaintainDynamicCaches setting by right clicking the output cell bracket and using the properties inspector. Unfortunately neither of these settings seemed to fix it. Thank you though! – Dan Apr 26 '17 at 20:31
• So the memory grows as you would import all at once in opposite to expected one row size? – Kuba Apr 26 '17 at 21:39
• It does grow one page at a time (e.g., 20 images per slide) but if you view all slides it actually uses more memory than just Importing all of the images directly. – Dan Apr 27 '17 at 2:51