I have a suspected memory leak - I am reading from and writing to files within one class - perhaps the data isn't being released - not sure I need to run some tests.

However, I am looking into using a destructor in my class which I will use to set all injected objects in my constructor to null.

I am also going to use finally after my try {} catch {} blocks, so I can ensure all locally created objects have been freed - and any file connections have been closed. This will ensure (I hope) that all objects have been cleared.

Does anyone have any objections to this? I am just asking because I haven't really seen any of this type of thing in core Magento.

有帮助吗?

解决方案

However, I am looking into using a destructor in my class which I will use to set all injected objects in my constructor to null.

This will not have any effect. The destructor is called when the object is released from memory because it is not used (referenced) anymore. That means, after __destruct the object and its attributes do not exist anymore. Setting the attributes to null before they cease to exist is useless.

If the injected objects were only referenced in this particular object, garbage collection will take care of them. But by default, injected objects are shared, so the object manager holds a reference for the whole request and the objects are not "destructed" until the very end.

If you have objects that hold lots of data in memory, and want to free that after usage, do not inject them directly. Inject an automatically generated Factory instead. This way you can control when to create the actual object and all references to it.

I am also going to use finally after my try {} catch {} blocks, so I can ensure all locally created objects have been freed - and any file connections have been closed. This will ensure (I hope) that all objects have been cleared.

For locally created objects, this is not necessary, for similar reasons. As soon as the method finished executing, the local scope does not exist anymore, and if the objects are not used anywhere else, they are gone. For resources, like open files however, this is a good idea and you should do it: make sure to always close every file that you open.

许可以下: CC-BY-SA归因
scroll top