I have written a c++ module that I want to use in Python, using pybind11. It contains, amongst other, this code:
class Foo{
...
void Foo::Bar(BigObject& returnBigObject)
{
for (int i=0; i<4; i++)
{
BigObject tempObject;
//doStuffWithTempObject
returnBigObject += tempObject;
}
}
};
Now, I have exposed this code to python and it functions as expected. However when I look at the memory usage, I see that when the BigObject tempobject
goes out of scope the memory is not always freed. Meaning that If I look at psutil.Process(os.getpid()).memory_info().rss
the memory does not go down to what I expect. After some debugging I traced it back to this temporary BigObject
.
Also I see this behaviour on Linux, but not on Windows, and on Linux it happening depends a lot on the code that I write before the call to this function.
My question is, is this normal behaviour of a managed language like Pyhton? Should I worry about memory usage in this case or trust the garbagecollector to clean up the memory when the application needs it to? Does the garbage collector even handle this kind of stuff, or there a different mechanism at play?