Mathematica is [known](https://mathematica.stackexchange.com/a/221520/85954) not to garbage collect temporary variables in certain cases. I am particularly interested in the very useful programming pattern known as a [lexical closure](https://en.wikipedia.org/wiki/Closure_(computer_programming)). A somewhat trivial example is

```
getMultiplier[n_] := Module[{f},
  f[x_] := n*x;
  f
];

```

Defining `M = getMultiplier[4]` returns a function that multiplies by 4, for example `M[5]` will return 20. But if one removes the symbol `M` by calling `Remove[M]` then the temporary variable `f` that it referred to will remain in memory and not be garbage collected. This is also true with `$HistoryLength = 0`.

**Question:** *What workarounds can be used to avoid the memory leak that comes with this programming pattern (lexical closure) in Mathematica?* I include two workarounds, but I hope somebody has a more general and more robust solution.

**Workaround 1:** Avoid generating temporary variables in the first place, using an anonymous function as in

```
getMultiplier[n_] := (n*#&);

```

This workaround has various limitations, for example it prohibits common Mathematica patterns such as memoization `f[x_] := f[x] = n*x`.

**Workaround 2:** Explicitly include a remover function as in

```
getMultiplier[n_] := Module[{f},
  f[x_] := n*x;
  f["remove"] := Remove[f];
  f
];

```

One can call `M = getMultiplier[4]`, use it a bunch of times, then call `M["remove"]` just before calling `Remove[M]`, and no memory leak occurs. This workaround amounts to manual memory management, and is both inconvenient and error-prone in larger programs, say when one closure refers to another closure and so on.

**Edit:** If you are aware of low level commands or settings in the vicinity of the Mathematica garbage collector, that could conceivably help with the issue at hand, please point them out. The [Low-Level System Optimization Guide](https://reference.wolfram.com/language/guide/LowLevelSystemOptimization.html) shows that there is a `ClearSystemCache` command for example, which is not directly useful here, but if there was say a similar (perhaps hidden) command `ForceFullGarbageCollection` to force a more extensive garbage collection including variables such as `f` above when unreachable, then please point it out. Perhaps the garbage collector does not do this automatically for performance reasons, but can be encouraged to do it?