Page 1 of 1

How can I release memory that an image takes?

Posted: Fri Oct 07, 2016 8:12 am
by shimatsukaze
If I use

Code: Select all

love.graphics.newImage("asset/logo.png")
how can I release the memory after this image is no longer used?
I have to load lots of images, and I can't load them all at a time, as they are too large.
However, only about ten images will appear at one scene, so I wonder if I could release the memory after every scene and load new ones?
I mean, is there a way to load images before every scene and destroy them afterwards so as to save memory?

Re: How can I release memory that an image takes?

Posted: Fri Oct 07, 2016 9:22 am
by Roland_Yonaba
Normally Lua, takes care of it. I mean the garbage collector does.
You can help him by assigning nil to the reference which points to the image loaded. I mean, when the asset loaded is no longer used, assign nil to it. In that way, you are tagging this element so that the gabage collector, when it will run, will collect this asset and release it from memory, in case there are no longer any other valid reference to this object.
Of course, instead of waiting for the garbage collector to run, you can call it via collectgarbage(). But really, this is not really necessary in most practical cases.

Re: How can I release memory that an image takes?

Posted: Fri Oct 07, 2016 9:55 am
by shimatsukaze
Roland_Yonaba wrote:Normally Lua, takes care of it. I mean the garbage collector does.
You can help him by assigning nil to the reference which points to the image loaded. I mean, when the asset loaded is no longer used, assign nil to it. In that way, you are tagging this element so that the gabage collector, when it will run, will collect this asset and release it from memory, in case there are no longer any other valid reference to this object.
Of course, instead of waiting for the garbage collector to run, you can call it via collectgarbage(). But really, this is not really necessary in most practical cases.
Thank you, it works.
I didn't learn about garbage recycling in Lua; I thought I had to release it manually.
but if I don't run "collectgarbage()", the memory use will even increase to 1GB even if I assign nil to the object. Maybe because I was loading too many images while testing.
Whatever, "collectgarbage()" really helps me a lot. Thank you again.

Re: How can I release memory that an image takes?

Posted: Fri Oct 07, 2016 4:27 pm
by pgimeno
I've noticed that automatic garbage collection is a bit lazy, or maybe just slow, especially when there's high CPU consumption. If you generate a lot of garbage per frame (e.g. creating many tables on the fly that you pass as arguments to functions, or creating many temporary objects), it's advisable to run collectgarbage() in your love.update, to prevent stuttering.