Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Memmory leak if not disposing assets  (Read 2983 times)

0 Members and 1 Guest are viewing this topic.

Antonio9227

  • Newbie
  • *
  • Posts: 25
    • View Profile
Memmory leak if not disposing assets
« on: December 26, 2023, 11:29:20 pm »
This is totally my fault but I decided to write a post in here just in case somebody comes across this in the future.

I needed a small app that loads in a bunch of pictures (like..thousands of them) and does some very basic editing (such as rescaling, adding text, stuff like that). Decided to use SFML since I've used it a lot in the past.

Guess I got used to the Garbage Collection of .NET and didn't even think about this until my PC froze.

BEWARE! GarbageCollection does NOT work automatically on Textures (and I assume other stuff as well) unless you call the Dispose method. It doesn't seem to matter that you're technically no longer using the texture and you no longer have any reference to it.


// Will cause a memmory leak
public void DoStuff(string[] texturePaths) {
  foreach(var texturePath in texturePaths) {
    var texture = new Texture(texturePath);
    DoOtherStuff(texture);
  }
}


// memmory gets cleared on GC.Collect()
public void DoStuffSafely(string[] texturePaths) {
  foreach(var texturePath in texturePaths) {
    var texture = new Texture(texturePath);
    DoOtherStuff(texture);
    texture.Dispose(); // this. do this when you no longer need the texture
  }
}
 

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
Re: Memmory leak if not disposing assets
« Reply #1 on: December 30, 2023, 12:42:09 pm »
They're implemented as IDisposable, so you don't have to manually call Dispose() if you use a using block.

For example:
public void DoStuffSafely(string[] texturePaths) {
  foreach(var texturePath in texturePaths) {
    using var texture = new Texture(texturePath); // Will be "lowered" to a try-finally block calling Dispose
    DoOtherStuff(texture);
  }
}
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/