Freeing RAM after executing a function in a Python script

Hi everyone,

I’m running a Python script in Rhino, and I noticed that after executing certain functions, memory usage remains high. Is there a way to free up RAM after a function has finished executing?

I’ve tried using gc.collect(), but it doesn’t seem to have a noticeable effect. Are there any best practices or Rhino-specific methods to properly release memory?

Any insights would be greatly appreciated!

Thanks!

Might it be storing the undo info from the script? Does running the Rhino command ClearUndo clear the RAM afterwards?

Is this the memory used to hold a Python engine, that’s allocated the first time Python code needing that engine is loaded (you must have noticed the delay)?

Or is the Python script doing something that requires an enormous amount of RAM.

There’s a lot of Python code out there too, that could be rewritten to use much less RAM in the first place, e.g. by ditching unnecessary copies of variables.

This one for sure, like exploding several thousand blocks, and other comples tasks, but the script is already optimized to take the least amount of ram.

Ah OK. Is it the same in CPython? Other than del xing everything before calling gc.collect() as you are doing I can’t think what else you could do without example code to work from.

The IronPython engine in Grasshopper does retain and share some state between different Iron Python components, e.g. sys.modules. That might stop variables in imported modules being collected.

Hi,

I think without any code it is hard to tell. But three not so obvious pitfalls for IronPython:

1.) “gc.collect()” will only work if there are no references in use anymore. An IronPython script remains in memory, since its compiled as a in-memory dll. If you store references inside a static collection you can quickly create a memory leak. Usually you should remove all references in use, otherwise the instances cannot be collected. In case you are uncertain you can use a “WeakReference<T>” in such collection . Better is to prevent preserving references. If this is the case here… Of course it can still be an Rhino bug. Memory leaks were reported for v8.

2.) If the object implements the IDisposable interface, then its your task to “Dispose” the instance. Say you open a memory stream, it remains open until you explicitly close it. Therefore the GC will never collect it.

3.) If you dismantle meshes, blocks, point-clouds etc you might create less optimised data. This automatically increases memory usage, even if the geometry looks the same. Do not underestimate Rhino-internal optimisation which you can easily break by dismantling geometrical shapes.

1 Like