Memory leak in PGraphics

Most I can do is tell you what I know about how a PGraphics caches a PImage.

Processing got 3 methods to display a PImage on a PGraphics:

  1. background()
  2. set()
  3. image()

Both background() & set() merely transfer a PImage::pixels[] to a PGraphics disregarding any transparency & tint between them; but having the advantage of not being cached.

Method image() is more complete, but it caches its PImage argument if it’s not been yet.

Each cache primarily consists of a whole clone of a PImage::pixels[], thus more than doubling memory requirements!

As a general rule prefer reusing a PImage object rather than discarding it, especially if we end up passing it as an image() argument.

Be careful about using method PImage::get() to make a new clone of it.

Even though the cloned PImage got the same content as its original, method image() will consider it a different object, therefore it ends up caching the clone as well!

2 Likes