Increasing memory usage after repeated margins calls in Stata
0 reputation · 20 Sept 2021, 04:49 UTC
0 reputation · 20 Sept 2021, 04:49 UTC
Goal: Determine whether the memory increase observed after repeated calls to the margins command in Stata reflects a true leak or expected caching of intermediate results, and whether clearing that memory requires a manual Mata workspace reset.
Constraints: Reports differ across Stata versions; Stata 18 changed internal memory‑management for margins, but certain options such as at() or contrast() may still leave temporary Mata objects, and clear all does not affect Mata workspace.
Questions: Does the margins command in Stata 18 retain temporary Mata objects after each call when using at() or contrast() options? Is the observed memory growth after repeated margins calls attributable to caching rather than a leak, and does executing mata drop _all fully release that memory? Are there any documented settings or commands that guarantee release of margins‑related temporaries without ending the session?
35275 reputation · 20 Sept 2021, 09:34 UTC
Yes – in Stata 18 the margins command retains temporary Mata objects created for at() or contrast() specifications after each execution. The observed increase in memory usage is therefore due to caching of those temporaries, not a traditional memory leak. Running mata drop _all (or mata clear) removes all user‑defined Mata objects, including the margins‑related temporaries, and returns the Mata workspace to its initial state. Stata provides no built‑in option to automatically discard these temporaries; the recommended way to free them is to execute mata drop _all after a block of margins calls or at the end of your do‑file.
at() and contrast() specifications so that subsequent margins calls can reuse them if needed. This caching appears as rising memory usage.margins call when at() or contrast() options are used.mata drop _all clears all user‑defined Mata objects, releasing the cached memory.margins option that automatically discards these temporaries.memorymargins calls (e.g., a loop with at() or contrast()).memory – you should see an increase.mata drop _all.memory once more; memory should return close to the baseline.mata describe to confirm the temporaries are gone.If you have Mata functions, matrices, or other objects that you need to preserve, please let us know so we can advise on a selective drop or alternative workflow.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.